iOS开发完全自定义数据转模型(ZHModel)

利用KVC原理完全自定义数据转模型, 更多功能长期迭代更新中

用法 : 

1 > 新建你的model类然后继承ZHModel

2 > 新建model中, 写入你的属性

3 > 然后调用对象方法就可直接解析

github地址 : https://github.com/ZHHalsey/ZHModel

核心代码:

核心代码

- (void)ZH_setValue:(nullableid)value forKey:(NSString*)key{

    if(key ==nil|| key.length==0) {

        NSLog(@"传入的key为nil或者key长度为0");

        return;

    }

    [selfsetValue:valueforKey:key];

    NSString *setKey = [NSString stringWithFormat:@"set%@:", key.capitalizedString];

    NSString *setIsKey = [NSString stringWithFormat:@"setIs%@:", key.capitalizedString];

    if([self respondsToSelector:NSSelectorFromString(setKey)]){

        [self performSelector:NSSelectorFromString(setKey) withObject:value];

        return;

    }

    if([self respondsToSelector:NSSelectorFromString(setIsKey)]){

        [self performSelector:NSSelectorFromString(setIsKey) withObject:value];

        return;

    }

    if (![self.class accessInstanceVariablesDirectly]){

        // 异常

        NSException *exception = [NSException exceptionWithName:@"ZH_EXCEPTION" reason:[NSString stringWithFormat:@"你没有实现这个key:'%@'的setter方法, 而且你还不允许访问成员变量", key] userInfo:nil];

        @throwexception;

        return;

    }

    unsignedintcount =0;

    Ivar*ivars =class_copyIvarList(self.class, &count);

    NSMutableArray *ivarArr = [NSMutableArray arrayWithCapacity:0];

    for(inti =0; i < count; i++) {

        Ivarivar = ivars[i];

        constchar*bianlaing_name =ivar_getName(ivar);

        [ivarArraddObject:[NSStringstringWithFormat:@"%s", bianlaing_name]];

    }

    for(inti =0; i < count; i++) {

        NSString*keyName = ivarArr[i];

        Ivarivar = ivars[i];

        if([keyNameisEqualToString:[NSStringstringWithFormat:@"_%@", key]]) {

            object_setIvar(self, ivar, value);

            free(ivars);

            return;

        }

    }

    for(inti =0; i < count; i++) {

        NSString*keyName = ivarArr[i];

        Ivarivar = ivars[i];

        if([keyNameisEqualToString:[NSStringstringWithFormat:@"_is%@", key.capitalizedString]]) {

            object_setIvar(self, ivar, value);

            free(ivars);

            return;

        }

    }

    for(inti =0; i < count; i++) {

        NSString*keyName = ivarArr[i];

        Ivarivar = ivars[i];

        if([keyNameisEqualToString:[NSStringstringWithFormat:@"%@", key]]) {

            object_setIvar(self, ivar, value);

            free(ivars);

            return;

        }

    }

    for(inti =0; i < count; i++) {

        NSString*keyName = ivarArr[i];

        Ivarivar = ivars[i];

        if([keyNameisEqualToString:[NSStringstringWithFormat:@"is%@", key.capitalizedString]]) {

            object_setIvar(self, ivar, value);

            free(ivars);

            return;

        }

    }

    [self setValue:value forUndefinedKey:key];

    free(ivars);

}

推荐阅读更多精彩内容