Reputation: 305
I am having trouble with my Objective-C code. I am trying to print out all of the details of my object created from my "Person" class, but the first and last names are not coming through in the NSLog method. They are replaced by spaces.
Person.h: http://pastebin.com/mzWurkUL Person.m: http://pastebin.com/JNSi39aw
This is my main source file:
#import <Foundation/Foundation.h>
#import "Person.h"
int main (int argc, const char * argv[])
{
Person *bobby = [[Person alloc] init];
[bobby setFirstName:@"Bobby"];
[bobby setLastName:@"Flay"];
[bobby setAge:34];
[bobby setWeight:169];
NSLog(@"%s %s is %d years old and weighs %d pounds.",
[bobby first_name],
[bobby last_name],
[bobby age],
[bobby weight]);
return 0;
}
Upvotes: 0
Views: 117
Reputation: 15767
%s is for C style strings (a sequence of chars terminated by a null).
Use %@ for NSString objects. In general, %@ will invoke the description instance method of any Objective C object. In the case of NSString, this is the string itself.
On an unrelated note, you should look into Declared Properties and @synthesize for your class implementation. It will save you a lot of typing as it produces all the getters and setters for you:
person.h:
#import <Cocoa/Cocoa.h>
@interface Person : NSObject
@property (nonatomic, copy) NSString *first_name, *last_name;
@property (nonatomic, strong) NSNumber *age, *weight;
@end
person.m
#import "Person.h"
@implementation Person
@synthesize first_name = _first_name, last_name = _last_name;
@synthesize age = _age, weight = _weight;
@end
main.m
#import <Foundation/Foundation.h>
#import "Person.h"
int main (int argc, const char * argv[])
{
Person *bobby = [[Person alloc] init];
bobby.first_name = @"Bobby";
bobby.last_name = @"Flay";
bobby.age = [NSNumber numberWithInt:34]; // older Objective C compilers.
// New-ish llvm feature, see http://clang.llvm.org/docs/ObjectiveCLiterals.html
// bobby.age = @34;
bobby.weight = [NSNumber numberWithInt:164];
NSLog(@"%@ %@ is %@ years old and weighs %@ pounds.",
bobby.first_name, bobby.last_name,
bobby.age, bobby.weight);
return 0;
}
Upvotes: 6