描述方法没有被调用

问题描述:

我创建了一个例子来学习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

您可能需要调用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