NSObject+UserModel.m 2.75 KB
//
//  NSObject+UserModel.m
//  CNLiveUserSystemDemo
//
//  Created by iOS on 16/9/18.
//  Copyright © 2016年 zhulin. All rights reserved.
//

#import "NSObject+UserModel.h"
#import <objc/runtime.h>

//static const char *key = "propertiesKey";

@implementation NSObject (UserModel)

+(instancetype)modelWithKeyValues:(NSDictionary *)dict
{
    id model = [[self alloc]init];
    
#pragma mark - 遍历properties
    
    unsigned int count ;
    objc_property_t *properties =  class_copyPropertyList([self class], &count);
    for ( int i = 0; i < count; i++) {
        objc_property_t property = properties[i];
        
        // 获取type
        NSString *type = [NSString stringWithUTF8String:property_getAttributes(property)];
        // 获取key
        NSString *key = [NSString stringWithUTF8String:property_getName(property)];
        
        // 通过key 从字典中取值
        id value = dict[key];
        
        // 判断值得类型 ,不是字典类型 ,是对象类型 : T@"NSDictionary" : 现在要获取他的对象类型,不是字典,是模型。擦
#pragma mark - 嵌套的对象--> 获取对象类名, 字典转模型
        if (![type containsString:@"NS"] && [value isKindOfClass:[NSDictionary class]]) {
            NSRange range = [type rangeOfString:@"@\""]; // 转义
            //  NSDictionary"
            type = [type substringFromIndex:range.location + range.length];
            range = [type rangeOfString:@"\""]; // 后面的的双引号
            NSString *modelstring = [type substringToIndex:range.location];
            
            // 获取class
            Class modelClass = NSClassFromString(modelstring);
            
            if (modelClass) { // 如果有值
                value = [modelClass modelWithKeyValues:value];
            }
        }
        
#pragma mark - 数组中得字典,也要转换成对象模型
        if ([value isKindOfClass:[NSArray class]]) {
            if ([self respondsToSelector:@selector(arrayContainModelClass)]) { // 实现了这个协议
                id idSelf = self;
                NSString *type = [idSelf arrayContainModelClass][key];
                Class modelClass = NSClassFromString(type);
                NSMutableArray *tempArray = [NSMutableArray array];
                
                // 遍历这个数组
                for (NSDictionary *dict in value) {
                    id arrayModel = [modelClass modelWithKeyValues:dict];
                    [tempArray addObject:arrayModel];
                }
                value = tempArray; // 里面装的都是对象
            }
        }
        
        if (value) { // 有值我才赋值,没值就忽略
            [model setValue:value forKey:key];
        }
    }
    
    free(properties); // 释放
    return model;
}

@end