0

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

1 回答 1

6

%s 用于 C 风格的字符串(以 null 结尾的字符序列)。

将 %@ 用于 NSString 对象。通常,%@ 将调用任何 Objective C 对象的描述实例方法。对于 NSString,这是字符串本身。

请参阅字符串格式说明符

在不相关的说明中,您应该查看Declared Properties和 @synthesize 以实现您的类实现。它会为您生成所有 getter 和 setter,从而为您节省大量输入:

人.h:

#import <Cocoa/Cocoa.h>

@interface Person : NSObject
@property (nonatomic, copy) NSString *first_name, *last_name;
@property (nonatomic, strong) NSNumber *age, *weight;
@end

人.m

#import "Person.h"

@implementation Person
@synthesize first_name = _first_name, last_name = _last_name;
@synthesize age = _age, weight = _weight; 
@end

主文件

#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;
}
于 2012-06-30T03:01:38.387 回答