2017-08-10 123 views
0

我創建了一個例子來學習objective-c中的一些基礎知識。我有一個叫Person的類,如下所示。在main方法我打電話description方法來打印一些數據,並且據我所知,description method類似於toString在java..but description方法我創建不叫描述方法沒有被調用

請看看下面的代碼,讓我知道爲什麼description方法的內容沒有被調用。

person.h

#import <Foundation/Foundation.h> 

@interface Person : NSObject { 
    int age; 
    int weight; 
} 

-(void) setAge:(int) age; 
-(void) setWeight: (int) weight; 

-(int) getAge; 
-(int) getWeight; 

-(NSString *) description; 

@end 

person.m

#import "Person.h" 

@implementation Person 

-(void) setAge:(int) a { 
    age = a; 
} 

-(void) setWeight:(int) w { 
    weight = w; 
} 

-(int) getAge { 
    return age; 
} 

-(int) getWeight { 
    return weight; 
} 

-(NSString *) description { 
    NSString *desc = @("my age is: %i and my weight is: %i", age, weight); 
    NSLog(@"%@", desc); 
    return desc; 
} 
@end 

主要

#import <UIKit/UIKit.h> 
#import "AppDelegate.h" 
#import "Person.h" 

int main(int argc, char * argv[]) { 
    @autoreleasepool { 

     Person *me = [[Person alloc] init]; 

     [me setAge:20]; 
     [me setWeight:55]; 

     NSString *desc = [me description]; 
     NSLog(@"%@", desc); 

     return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 
    } 
} 
+0

你檢查,把___break point___在你的代碼?或者你沒有得到日誌消息,並假設該方法根本沒有被調用? – nayem

+0

@nayem這就是爲什麼我添加NSLog裏面的描述方法.. slog消息不打印 – user2121

+0

'NSString * desc = @(「我的年齡是:%我和我的體重是:%我」,年齡,體重);'這是一種奇怪的方法來創建'NSString'' stringWithFormat:'。 – Larme

回答

0

您可能需要調用description方法,但您沒有收到日誌消息。問題出在你製作的NSString上。這是無效的:

NSString *desc = @("my age is: %i and my weight is: %i", age, weight); 

嘗試改變這一到:

NSString *desc = [NSString stringWithFormat:@"my age is: %i and my weight is: %i", age, weight]; 
+0

你認爲我應該在person.h中添加描述方法的簽名? – user2121

+0

' - (NSString *)description'和'+(NSString *)description'是'NSObject'的方法。所以它們在所有的子類中都被繼承。所以你基本上不需要將簽名添加到頭文件中。 – nayem