描述方法没有被调用
问题描述:
我创建了一个例子来学习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]));
}
}
答
您可能需要调用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];
你检查,把___break point___在你的代码?或者你没有得到日志消息,并假设该方法根本没有被调用? – nayem
@nayem这就是为什么我添加NSLog里面的描述方法.. slog消息不打印 – user2121
'NSString * desc = @(“我的年龄是:%我和我的体重是:%我”,年龄,体重);'这是一种奇怪的方法来创建'NSString'' stringWithFormat:'。 – Larme