跟C++的输出函数相比,NSlog函数有个很大的优势,就是它可以输出对象。
在实际使用过程中,我们可以通过实现description函数来实现对NSLog函数的重写
-(NSString*)description
NSString *ret=[NSStringstringWithFormat :@”name= %@,age=%@”,self .name ,self .age ];
return ret;
具体sample如下:
import
@interface person : NSObject
@property (nonatomic ,retain )NSString *name;
@property (nonatomic ,retain )NSNumber *age;
@end
person.m文件:
import”person.h”
@implementation person
-(NSString*)description
NSString *ret=[NSStringstringWithFormat :@”name= %@,age=%@”,self .name ,self .age ];
return ret;
-(void)dealloc
[_name release];
[_age release];
[super dealloc];
@end
main函数:
int main(int argc, const char * argv[])
@autoreleasepool {
person *personObj=[[person alloc] init];
personObj.name=@”andy”;
personObj.age=[NSNumber numberWithInt:34];
NSLog(@”the obj is %@”,personObj);
return 0;
输出结果:
2013-11-14 14:31:17.730 elementFirst[2824:303] the obj is name= andy,age=34
Original: https://www.cnblogs.com/keanuyaoo/p/3424178.html
Author: 风言枫语
Title: NSLog函数重写
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/552283/
转载文章受原作者版权保护。转载请注明原作者出处!