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

来源:互联网 发布:哈尔滨php在哪找工作 编辑:程序博客网 时间:2024/04/29 09:59

做的时候经常发现一个viewModel类有几十个属性,初始化赋值太麻烦还耗时间,所以就想到runtime,进行批量赋值

要包含头文件:

#import <objc/runtime.h>



具体语句方法

- (instancetype)initWithModel:(id)model {

self = [superinit];

if (!self) {

returnnil;

}

_model = model;

unsignedint propertyCount = 0;

objc_property_t *properties =class_copyPropertyList([selfclass], &propertyCount);

for (unsignedint i = 0; i < propertyCount; i ++ ) {

objc_property_t property = properties[i];

constchar *name = property_getName(property);

constchar *attributes = property_getAttributes(property);

NSString *key = [NSStringstringWithUTF8String:name];

NSString *type = [NSStringstringWithUTF8String:attributes];

if ([typerangeOfString:@"NSString"].location !=NSNotFound ) {

[selfsetValue:@""forKey:key];

}

}

//RAC(self, catId) =

returnself;

}

这得节约多少时间,时间就是生命,时间就是金钱

0 0
原创粉丝点击