i’m starting to learn Objective C from today actually. I have a very little program which will print my name and age. I get the age to be printed but not the name. Instead of printing the name as a String it prints a number. Here’s the code:
#import <Foundation/Foundation.h>
@interface Person : NSObject {
NSString *name;
int age;
}
-(void) setAge:(int)a;
-(void) setName:(NSString*) n;
-(int)age;
-(NSString*) name;
-(void) print;
@end
@implementation Person
-(void)setAge:(int) a{
age = a;
}
-(void)setName:(NSString*) n{
[n retain];
[name release];
name = n;
}
-(int)age{
return age;
}
-(NSString*) name{
return name;
}
-(void) print{
NSLog(@"I'm %i, i'm %i years old", name, age);
}
@end
int main (int argc, char *argv[]){
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc]init];
Person *p = [[Person alloc]init];
[p setAge: 26];
[p setName: @"Johnny"];
[p print];
[pool drain];
return 0;
}
From that i get this print: I’m 4176, i’m 26 years old.
Why i’m i getting the 4176?
I don’t understand 🙁
Thanks in advance
By using the format string
%iyou are tellingNSLogthat you want to print an integer, and it is printing the address in memory of the string (that is, the value of pointername). Change your format string to tell it you want to print the string representation of the object pointed to byname, by using%@: