OC:打印自定义的类的属性信息
2018-11-20 本文已影响12人
春暖花已开
#import <Foundation/Foundation.h>
@interface MZBaseModel : NSObject
@end
#import "MZBaseModel.h"
#import <objc/runtime.h>
@implementation MZBaseModel
#ifdef DEBUG
- (NSString *)description {
id modelClass = [self class];
unsigned int count, i;
objc_property_t *properties = class_copyPropertyList(modelClass, &count);
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:count];
//遍历出所有的属性key/value
for (i = 0; i < count; i++) {
objc_property_t property = properties[i];
NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
id value = [[self valueForKey:propertyName] description];
[dict setObject:value forKey:propertyName];
}
return [NSString stringWithFormat:@"<%@: %p> %@", [self class], self, dict];
}
#endif
@end