2012-06-30 21 views
0

我遇到了我的Objective-C代碼問題。我試圖打印出從我的「Person」類創建的對象的所有細節,但名字和姓氏在NSLog方法中沒有經過。它們被空格替換。我的Objective-C類有什麼問題?

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

回答

6

%s是對C風格的字符串(以空終止字符的序列) 。

將%@用於NSString對象。通常,%@將調用任何Objective C對象的描述實例方法。在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; 
} 
+0

非常感謝。我忘記了Objective-C字符串,數組等自身是對象。我還不是很瞭解你正在談論的@synthesize,但我正在通過YouTube學習。 – zgillis