美文网首页iOS开发
利用RunTime和KVC实现模型转换

利用RunTime和KVC实现模型转换

作者: 神奇李白 | 来源:发表于2020-05-28 18:00 被阅读0次

    实现思路

    1.通过runtime获取对象的所有属性

    objc_property_t *propertyList = class_copyPropertyList([self class], &count);

    2.遍历所有属性通过kvc赋值(难点:多层自定义类的转换)

    3.没了

    创建类别:
    NSObject+HYModel.h
    NSObject+HYModel.h

    .h

    /**字典转模型*/
    + (id)hy_modelWithDictionary:(NSDictionary *)dic;
    /**json转模型*/
    + (id)hy_modelWithJSON:(NSDictionary *)dic;
    

    .m

    /**字典转模型*/
    + (id)hy_modelWithDictionary:(NSDictionary *)dic{
        if (!dic || [dic isEqual:[NSNull null]] || ![dic isKindOfClass:[NSDictionary class]]) {
            return nil;
        }
        id model = [[self alloc] init];
        NSArray *allProperties = [self getAllProperties];
        [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            if ([allProperties containsObject:key]) {
                //kvc赋值
                [model setValue:obj forKey:key];
            }
        }];
        return model;
    }
    
    /**json转模型*/
    + (id)hy_modelWithJSON:(NSString *)json{
        NSDictionary *dic = [self dictionaryWithJSON:json];
        id model = [[self alloc] init];
        model = [self hy_modelWithDictionary:dic];
        return model;
    }
    
    
    #pragma mark - 私有方法
    /* 通过runtime获取对象的所有属性 */
    - (NSArray *)getAllProperties{
        unsigned int count;
        NSMutableArray *allPropertiesArray = [[NSMutableArray alloc]init];
        objc_property_t *propertyList = class_copyPropertyList([self class], &count);
        for (unsigned int i = 0; i < count; i++) {
            const char *propertyName = property_getName(propertyList[i]);
            [allPropertiesArray addObject:[NSString stringWithUTF8String:propertyName]];
        }
        //释放propertyList(C语言)
        free(propertyList);
        return allPropertiesArray;
    }
    
    /*通过rutime获取对象的类*/
    
    /* json转模型 */
    - (NSDictionary *)dictionaryWithJSON:(id)json {
        if (!json || json == (id)kCFNull) return nil;
        NSDictionary *dic = nil;
        NSData *jsonData = nil;
        if ([json isKindOfClass:[NSDictionary class]]) {
            dic = json;
        } else if ([json isKindOfClass:[NSString class]]) {
            jsonData = [(NSString *)json dataUsingEncoding : NSUTF8StringEncoding];
        } else if ([json isKindOfClass:[NSData class]]) {
            jsonData = json;
        }
        if (jsonData) {
            dic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
            if (![dic isKindOfClass:[NSDictionary class]]) dic = nil;
        }
        return dic;
    }
    

    相关文章

      网友评论

        本文标题:利用RunTime和KVC实现模型转换

        本文链接:https://www.haomeiwen.com/subject/meiuohtx.html