前言
平时开发中难免会自定义model,有时候调试的时候打印model只是一个地址,其实我们可以通过重写model类的description来打印出model类的属性。
实战
在model类或者在model基类里重写description:
- (NSString *)description{
unsigned int count;
const char *clasName = object_getClassName(self);
NSMutableString *string = [NSMutableString stringWithFormat:@"<%s: %p>:[ \n",clasName, self];
Class clas = NSClassFromString([NSString stringWithCString:clasName encoding:NSUTF8StringEncoding]);
Ivar *ivars = class_copyIvarList(clas, &count);
for (int i = 0; i < count; i++) {
@autoreleasepool {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
//得到类型
NSString *type = [NSString stringWithCString:ivar_getTypeEncoding(ivar) encoding:NSUTF8StringEncoding];
NSString *key = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
id value = [self valueForKey:key];
//确保BOOL值输出的是YES 或 NO
if ([type isEqualToString:@"B"]) {
value = (value == 0 ? @"NO" : @"YES");
}
[string appendFormat:@"\t%@: %@\n",[self deleteUnderLine:key], value];
}
}
[string appendFormat:@"]"];
return string;
}
/// 去掉下划线
- (NSString *)deleteUnderLine:(NSString *)string{
if ([string hasPrefix:@"_"]) {
return [string substringFromIndex:1];
}
return string;
}
调试的时候通过po打印model就会打印出对应属性和值:
(lldb) po model
<MM_Model: 0x174053110>:[
name: (null)
isAdult: YES
age: 24
score: 100
number: 0
]
总结
以上就是对打印model属性的一些总结,写的不好希望大家多多指正。