只要利用%@打印对象,就会调用description,可以通过在类中重写description方法,进行格式化输出
- 如果打印的是对象,就会调用对象方法description,减号开头的
- 如果打印的是类,就会调用类方法description,加号开头的
注意:
- 在description方法中尽量不要使用self来获取成员变量,容易造成死循环
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
@public
NSString *_name;
int _age;
double _height;
}
@end
@implementation Person
// 重写父类中的 description 方法
-(NSString *)description {
NSString *str = [NSString stringWithFormat:@"name --> %@ age -->%i height -->%lf", _name, _age, _height];
return str;
};
@end
int main(int argc, const char * argv[]) {
Person *person = [Person new];
person->_name = @"张三";
person->_age = 18;
person->_height = 1.85;
NSLog(@"%@", person); // name --> 张三 age -->18 height -->1.850000
return 0;
}