您的位置:首页 > 其它

使用runtime给属性批量初始化赋值

2016-03-08 10:43 405 查看
做的时候经常发现一个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;
}
这得节约多少时间,时间就是生命,时间就是金钱
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: