做的时候经常发现一个viewModel类有几十个属性,初始化赋值太麻烦还耗时间,所以就想到runtime,进行批量赋值
要包含头文件:
#import <objc/runtime.h>
具体语句方法
- (instancetype)initWithModel:(id)model {
self = [super init];
if (!self) {
return nil;
}
_model = model;
unsigned int propertyCount = 0;
objc_property_t *properties = class_copyPropertyList([self class], &propertyCount);
for (unsigned int i = 0; i < propertyCount; i ++ ) {
objc_property_t property = properties[i];
const char *name = property_getName(property);
const char *attributes = property_getAttributes(property);
NSString *key = [NSString stringWithUTF8String:name];
NSString *type = [NSString stringWithUTF8String:attributes];
if ([type rangeOfString:@"NSString"].location != NSNotFound ) {
[self setValue:@"" forKey:key];
}
}
//RAC(self, catId) =
return self;
}
这得节约多少时间,时间就是生命,时间就是金钱