跟C++的输出函数相比,NSlog函数有个很大的优势,就是它可以输出对象。
在实际使用过程中,我们可以通过实现description函数来实现对NSLog函数的重写
-(NSString*)description
{
NSString *ret=[NSStringstringWithFormat:@"name= %@,age=%@",self.name,self.age];
return ret;
}
具体sample如下:
#import <Foundation/Foundation.h>
@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