class_copyPropertyList不能获取到父类属性解
2017-07-05 本文已影响386人
Alfred_小乐
开发中为了debug方便,会重写 - (NSString *)description
方法,并用runtime
的class_copyPropertyList
函数得到属性名,并通过valueForKey
的方式获取name对应的value。
但是class_copyPropertyList
只能得到所传类的属性名数组,开发中用到的model经常是继承来的,如果想在debug是获取父类的属性值,怎么办?
其实思路很简单,我们只需要获取父类的属性数组,在遍历获取value就可以了。
上代码:
@implementation BaseModel
- (void)debugClass:(Class)cls PropertysWithDictionary:(NSMutableDictionary *)dic
{
if (![NSStringFromClass(cls.superclass) isEqualToString:NSStringFromClass([BaseModel class])]) {
uint count;
objc_property_t *properties = class_copyPropertyList(cls.superclass, &count);
for (int i = 0; i<count; i++) {
objc_property_t property = properties[i];
NSString *name = @(property_getName(property));
id value = [self valueForKey:name]?:@"nil"; [dic setObject:value forKey:name];// 注意使用self得到value
}
free(properties);
[self debugClass:(cls.superclass) PropertysWithDictionary:dic];
}
}
-(NSString *)description
{
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self debugClass:([self class]) PropertysWithDictionary:dictionary];
uint count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (int i = 0; i<count; i++) {
objc_property_t property = properties[i];
NSString *name = @(property_getName(property));
id value = [self valueForKey:name]?:@"nil"; [dictionary setObject:value forKey:name];
}
free(properties);
return [NSString stringWithFormat:@"<%@: %p> -- %@",[self class],self,dictionary];
}
@end
这样我们只在debug的时候打印到BaseModel
的属性,而不需要其他不必要的属性。