我的Objective-C课有什么问题?

时间:2012-06-30 03:00:18

标签: objective-c oop

我的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;
}

1 个答案:

答案 0 :(得分:6)

%s用于C样式字符串(由空值终止的字符序列)。

对NSString对象使用%@。通常,%@将调用任何Objective C对象的description实例方法。在NSString的情况下,这是字符串本身。

请参阅String Format Specifiers

在一个不相关的说明中,您应该查看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

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;
}