NSString won't work in Objective C
i'm starting to learn Objective C from today actually. I have a very little program which will print my name and age. I g开发者_开发问答et 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 %i
you are telling NSLog
that you want to print an integer, and it is printing the address in memory of the string (that is, the value of pointer name
). Change your format string to tell it you want to print the string representation of the object pointed to by name
, by using %@
:
NSLog(@"I'm %@, i'm %i years old", name, age);
How are you printing it? My bet is you are not printing it right. Try printing it in the log like this
NSLog(@"I'm %@, i'm %d years old", name, age);
Her's the table in case someone has same trouble NSString Formating Table
精彩评论