我创建了一些示例来学习objective-c中的一些基础知识。我有一个名为Person的类,如下所示。在主要方法中,我尝试调用description
方法来打印一些数据,而AFAIK,description method
与java toString
类似,我创建的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 :(得分: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];