利用RunTime和KVC实现模型转换

实现思路

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实现模型转换)