利用runtime解析model

来源:互联网 发布:海拔计指南针软件 编辑:程序博客网 时间:2024/04/29 07:04

利用runtime解析model

by 伍雪颖

+ (instancetype)modelWithDictionary: (NSDictionary*) data{
   
return [[selfalloc]initWithDictionary:data];
}

- (
instancetype)initWithDictionary: (NSDictionary*) data{
    {
       
self = [superinit];
       
if (self) {
            [
selfassginToPropertyWithDictionary:data];
        }
       
return self;
    }
}

-(
void) assginToPropertyWithDictionary: (NSDictionary*) data{
   
if (data == nil) {
       
return;
    }
   
NSArray *dicKey = [dataallKeys];
   
for (inti = 0; i < dicKey.count; i ++) {
       
SEL setSel = [selfcreatSetterWithPropertyName:dicKey[i]];
       
       
if ([selfrespondsToSelector:setSel]) {
           
NSString  *value = [NSStringstringWithFormat:@"%@", data[dicKey[i]]];
            [
selfperformSelectorOnMainThread:setSel
                                  
withObject:value
                               
waitUntilDone:[NSThreadisMainThread]];
        }
    }
}

- (
SEL) creatSetterWithPropertyName: (NSString*) propertyName{
    propertyName = propertyName.
capitalizedString;
    propertyName = [
NSStringstringWithFormat:@"set%@:", propertyName];
   
return NSSelectorFromString(propertyName);
}

1 0
原创粉丝点击