标签:
一、简介
与.NET一样,在.NET上得Object对象有个ToString()方法可以用于输出对象的信息,在iOS上的NSObject也有一个方法,为description,该方法返回objc对象的描述信息,当我们调用NSLog打印一个对象或者NSString格式化输出一个对象的时候,就会调用该方法,NSObject还有另一个方法debugDescription,用于在调试控制台输出信息(在控制台输出对象信息如:po person),默认情况下debugDescription调用的时description方法
二、演示
@interface Person : NSObject @property (nonatomic, assign) NSUInteger age; @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) NSUInteger gender; @property (nonatomic, assign) float weight; @end @implementation Person @end
Person *person = [[Person alloc] init];
person.name =@"bomo";
person.age = 24;
person.weight = 134;
NSString *logMessage = [NSString stringWithFormat:@"%@", person];
NSLog(@"stringWithFormat: %@", logMessage);
NSLog(@"nslog: %@", person);
默认情况下,object-c对象只输出对象名字和对象的地址
默认的实现应该是这样的
- (NSString *)description { return [NSString stringWithFormat:@"<%@: %p>", NSStringFromClass([self class]), self]; }
通常我们希望看到类的更多属性的信息,我们可以重写description方法
@interface Person : NSObject @property (nonatomic, assign) NSUInteger age; @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) NSUInteger gender; @property (nonatomic, assign) float weight; @end @implementation Person - (NSString *)description { return [NSString stringWithFormat:@"<Person: %p> {\n\tname=%@,\n\tage=%ld,\n\tweight=%f,\n\tgender=%lu\n}", self, self.name, self.age, self.weight, self.gender]; } @end
输出下面信息
三、封装
其实我们可以封装一个通用的方法,通过运行时的API动态获取到对象的类型,并输出,这里创建一个基类BaseModel,我们在基类实现一个通用的description方法
@interface BaseModel : NSObject @end @implementation BaseModel - (NSString *)description1 { id modelClass = [self class]; unsigned int outCount, i; objc_property_t *properties = class_copyPropertyList(modelClass, &outCount); NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:outCount]; //遍历出所有的属性key/value for (i = 0; i < outCount; i++) { objc_property_t property = properties[i]; NSString *propName = [NSString stringWithUTF8String:property_getName(property)]; id value = [[self valueForKey:propName] description]; [dict setObject:value forKey:propName]; } return [NSString stringWithFormat:@"<%@: %p> %@", NSStringFromClass([self class]), self, dict]; } - (NSString *)debugDescription { return [self description]; } @end
这是我们的Person类只需要继承自BaseModel即可实现如NSDictionary的输出,这里是利用的字典的输出,就不用自己拼字符串
上面通过基类的方式实现的自定义输出,还有另外一种方式也可以达到该目的,通过method swizzling换掉NSObject原来的description方法
参见:http://www.cnblogs.com/bomo/p/4693363.html
【iOS】desctiption和debugDescription
标签:
原文地址:http://www.cnblogs.com/bomo/p/4811906.html