我的Objective-C代码有问题.我试图打印出从我的"Person"类创建的对象的所有细节,但是在NSLog方法中不会出现名字和姓氏.它们被空格所取代.
Person.h:http ://pastebin.com/mzWurkUL Person.m:http://pastebin.com/JNSi39aw
这是我的主要源文件:
#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;
}
Run Code Online (Sandbox Code Playgroud)
%s用于C样式字符串(由null终止的字符序列).
将%@用于NSString对象.通常,%@将调用任何Objective C对象的description实例方法.在NSString的情况下,这是字符串本身.
请参见字符串格式说明符.
在一个不相关的注释中,您应该查看Declared Properties和@synthesize以获取类实现.它会为您节省大量的打字,因为它会为您生成所有的getter和setter:
person.h:
#import <Cocoa/Cocoa.h>
@interface Person : NSObject
@property (nonatomic, copy) NSString *first_name, *last_name;
@property (nonatomic, strong) NSNumber *age, *weight;
@end
Run Code Online (Sandbox Code Playgroud)
person.m
#import "Person.h"
@implementation Person
@synthesize first_name = _first_name, last_name = _last_name;
@synthesize age = _age, weight = _weight;
@end
Run Code Online (Sandbox Code Playgroud)
的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;
}
Run Code Online (Sandbox Code Playgroud)