iOS - 教你一步一步实现自己的字典转模型库

2,017 阅读5分钟
原文链接: www.jianshu.com

前言

我们在iOS开发中,一般会使用MVC或者MVVM等模式。当我们从接口中拿到数据时,我们需要把数据转成模型使用。下面我就带大家一起用runtime一步一步的来完成这个转换框架

1、先写一个简单的字典到模型的转换

  • 模型TestModel
@interface TestModel : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *phone;
@property (nonatomic, copy) NSString *address;
@property (nonatomic, assign) NSInteger age;

@end
  • 控制器ViewController中
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"字典转模型";

    NSDictionary *dicTest = @{@"name":@"张三",
                              @"phone":@"110",
                              @"age":@"10"};
    TestModel *model = [TestModel yj_initWithDictionary:dicTest];
    NSLog(@"model-----name:%@, phone:%@, address:%@, age:%@", model.name, model.phone, model.address, @(model.age));
}

@end
  • 字典转模型的分类中
@implementation NSObject (YJModelDicTransform)

//字典转模型
+ (instancetype)yj_initWithDictionary:(NSDictionary *)dic
{
    id myObj = [[self alloc] init];

    unsigned int outCount;

    //获取类中的所有成员属性
    objc_property_t *arrPropertys = class_copyPropertyList([self class], &outCount);

    for (NSInteger i = 0; i < outCount; i ++) {
        objc_property_t property = arrPropertys[i];

        //获取属性名字符串
        //model中的属性名
        NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
        id propertyValue = dic[propertyName];

        if (propertyValue != nil) {
            [myObj setValue:propertyValue forKey:propertyName];
        }
    }

    free(arrPropertys);

    return myObj;
}

//数组转模型数组,现在还用不了,因为还没有方法知道数组中保存的是什么类型,后面会处理
+ (instancetype)yj_initWithArray:(NSArray *)arr
{
    NSAssert([arr isKindOfClass:[NSArray class]], @"不是数组");

    NSMutableArray *arrModels = [NSMutableArray array];

    [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[NSArray class]]) {
            [arrModels addObject:[self yj_initWithArray:obj]];
        }
        else {
            id model = [self yj_initWithDictionary:obj];
            [arrModels addObject:model];
        }
    }];
    return arrModels;
}
  • 控制台打印

    2016-12-19 15:55:18.231 YJModelDicTransform[1627:125724] model-----name:张三, phone:110, address:(null), age:10

2、模型中嵌套有模型

  • 第一步完成后我们已经可以自动完成字典和模型的转换了,但是还不完善,比如我们的字典的value中如果有字典或者数组类型的话,程序就识别不了,所以我们现在就来处理这种情况

  • 先通过runtime来获取模型中属性的类型,然后根据不同类型来处理

@interface TestModel : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *phone;
@property (nonatomic, copy) NSString *address;

@property (nonatomic, assign) NSInteger age;
//模型中嵌套UserModel模型
@property (nonatomic, strong) UserModel *user;

@end

@interface UserModel : NSObject

@property (nonatomic, copy) NSString *userName;
@property (nonatomic, copy) NSString *userId;

@end
NSString *const YJClassType_object  =   @"对象类型";
NSString *const YJClassType_basic   =   @"基础数据类型";
NSString *const YJClassType_other   =   @"其它";
@implementation NSObject (YJModelDicTransform)

+ (instancetype)yj_initWithDictionary:(NSDictionary *)dic
{
    id myObj = [[self alloc] init];

    unsigned int outCount;

    //获取类中的所有成员属性
    objc_property_t *arrPropertys = class_copyPropertyList([self class], &outCount);

    for (NSInteger i = 0; i < outCount; i ++) {
        objc_property_t property = arrPropertys[i];

        //获取属性名字符串
        //model中的属性名
        NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
        id propertyValue = dic[propertyName];

        if (propertyValue == nil) {
            continue;
        }

        //获取属性是什么类型的
        NSDictionary *dicPropertyType = [self propertyTypeFromProperty:property];
        NSString *propertyClassType = [dicPropertyType objectForKey:@"classType"];
        NSString *propertyType = [dicPropertyType objectForKey:@"type"];
        if ([propertyType isEqualToString:YJClassType_object]) {
            if ([propertyClassType isEqualToString:@"NSArray"] || [propertyClassType isEqualToString:@"NSMutableArray"]) {
                //数组类型,现在还用不了,因为还没有方法知道数组中保存的是什么类型,后面会处理

            }
            else if ([propertyClassType isEqualToString:@"NSDictionary"] || [propertyClassType isEqualToString:@"NSMutableDictionary"]) {
                //字典类型   不考虑,一般不会用字典,用自定义model

            }
            else if ([propertyClassType isEqualToString:@"NSString"]) {
                //字符串类型
                if (propertyValue != nil) {
                    [myObj setValue:propertyValue forKey:propertyName];
                }
            }
            else {
                //自定义类型,循环调用,一直到不是自定义类型
                propertyValue = [NSClassFromString(propertyClassType) yj_initWithDictionary:propertyValue];
                if (propertyValue != nil) {
                    [myObj setValue:propertyValue forKey:propertyName];
                }
            }
        }
        else if ([propertyType isEqualToString:YJClassType_basic]) {
            //基本数据类型
            if ([propertyClassType isEqualToString:@"c"]) {
                //bool类型
                NSString *lowerValue = [propertyValue lowercaseString];
                if ([lowerValue isEqualToString:@"yes"] || [lowerValue isEqualToString:@"true"]) {
                    propertyValue = @(YES);
                } else if ([lowerValue isEqualToString:@"no"] || [lowerValue isEqualToString:@"false"]) {
                    propertyValue = @(NO);
                }
            }
            else {
                propertyValue = [[[NSNumberFormatter alloc] init] numberFromString:propertyValue];
            }

            if (propertyValue != nil) {
                [myObj setValue:propertyValue forKey:propertyName];
            }
        }
        else {
            //其他类型
        }
    }

    free(arrPropertys);

    return myObj;
}

//获取属性的类型
- (NSDictionary *)propertyTypeFromProperty:(objc_property_t)property
{
    //获取属性的类型, 类似 T@"NSString",C,N,V_name    T@"UserModel",&,N,V_user
    NSString *propertyAttrs = @(property_getAttributes(property));

    NSMutableDictionary *dicPropertyType = [NSMutableDictionary dictionary];

    //截取类型
    NSRange commaRange = [propertyAttrs rangeOfString:@","];
    NSString *propertyType = [propertyAttrs substringWithRange:NSMakeRange(1, commaRange.location - 1)];
    NSLog(@"属性类型:%@, %@", propertyAttrs, propertyType);

    if ([propertyType hasPrefix:@"@"] && propertyType.length > 2) {
        //对象类型
        NSString *propertyClassType = [propertyType substringWithRange:NSMakeRange(2, propertyType.length - 3)];
        [dicPropertyType setObject:propertyClassType forKey:@"classType"];
        [dicPropertyType setObject:YJClassType_object forKey:@"type"];
    }
    else if ([propertyType isEqualToString:@"q"]) {
        //NSInteger类型
        [dicPropertyType setObject:@"NSInteger" forKey:@"classType"];
        [dicPropertyType setObject:YJClassType_basic forKey:@"type"];
    }
    else if ([propertyType isEqualToString:@"d"]) {
        //CGFloat类型
        [dicPropertyType setObject:@"CGFloat" forKey:@"classType"];
        [dicPropertyType setObject:YJClassType_basic forKey:@"type"];
    }
    else if ([propertyType isEqualToString:@"c"]) {
        //BOOL类型
        [dicPropertyType setObject:@"BOOL" forKey:@"classType"];
        [dicPropertyType setObject:YJClassType_basic forKey:@"type"];
    }
    else {
        [dicPropertyType setObject:YJClassType_other forKey:@"type"];
    }
    return dicPropertyType;
}
  • 控制器中
- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"字典转模型";

    NSDictionary *dicTest = @{@"name":@"张三",
                              @"phone":@"110",
                              @"age":@"10",
                              @"user":@{@"userId":@"2"}};
    TestModel *model = [TestModel yj_initWithDictionary:dicTest];
    NSLog(@"model-----name:%@, phone:%@, address:%@, age:%@, userId:%@, userName:%@", model.name, model.phone, model.address, @(model.age), model.user.userId, model.user.userName);
}
  • 控制台打印

    2016-12-19 16:39:52.079 YJModelDicTransform[1851:143085] 属性类型:T@"NSString",C,N,V_name, @"NSString"
    2016-12-19 16:39:52.080 YJModelDicTransform[1851:143085] 属性类型:T@"NSString",C,N,V_phone, @"NSString"
    2016-12-19 16:39:52.080 YJModelDicTransform[1851:143085] 属性类型:Tq,N,V_age, q
    2016-12-19 16:39:52.081 YJModelDicTransform[1851:143085] 属性类型:T@"UserModel",&,N,V_user, @"UserModel"
    2016-12-19 16:39:52.081 YJModelDicTransform[1851:143085] 属性类型:T@"NSString",C,N,V_userId, @"NSString"
    2016-12-19 16:39:52.081 YJModelDicTransform[1851:143085] model-----name:张三, phone:110, address:(null), age:10, userId:2, userName:(null)

3、处理模型中有数组属性的情况

  • 第二步之后程序可以处理模型中包含模型的情况, 但是还不能处理模型中有数组的情况,因为数组中存储的类型需要人为的告诉程序,下面我们添加一个协议来来处理这种情况

  • 先创建一个协议, 然后让分类遵循它

@protocol YJModelDicTransform 

@optional

/**
 *  数组中存储的类型
 *
 *  @return key --- 属性名,  value --- 数组中存储的类型
 */
+ (NSDictionary *)yj_objectClassInArray;

@end

@interface NSObject (YJModelDicTransform)

+ (instancetype)yj_initWithDictionary:(NSDictionary *)dic;

@end
  • 在model中实现这个方法
@implementation TestModel

+ (NSDictionary *)yj_objectClassInArray
{
    return @{@"arrUsers":@"UserModel"};
}

+ (NSDictionary *)yj_propertykeyReplacedWithValue
{
    return @{@"_id":@"id"};
}

@end
//字典转模型
+ (instancetype)yj_initWithDictionary:(NSDictionary *)dic
{
    id myObj = [[self alloc] init];

    unsigned int outCount;

    //获取类中的所有成员属性
    objc_property_t *arrPropertys = class_copyPropertyList([self class], &outCount);

    for (NSInteger i = 0; i < outCount; i ++) {
        objc_property_t property = arrPropertys[i];

        //获取属性名字符串
        //model中的属性名
        NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
        id propertyValue = dic[propertyName];

        if (propertyValue == nil) {
            continue;
        }

        //获取属性是什么类型的
        NSDictionary *dicPropertyType = [self propertyTypeFromProperty:property];
        NSString *propertyClassType = [dicPropertyType objectForKey:@"classType"];
        NSString *propertyType = [dicPropertyType objectForKey:@"type"];
        if ([propertyType isEqualToString:YJClassType_object]) {
            if ([propertyClassType isEqualToString:@"NSArray"] || [propertyClassType isEqualToString:@"NSMutableArray"]) {
                //数组类型
                if ([self respondsToSelector:@selector(yj_objectClassInArray)]) {
                    id propertyValueType = [[self yj_objectClassInArray] objectForKey:propertyName];
                    if ([propertyValueType isKindOfClass:[NSString class]]) {
                        propertyValue = [NSClassFromString(propertyValueType) yj_initWithArray:propertyValue];
                    }
                    else {
                        propertyValue = [propertyValueType yj_initWithArray:propertyValue];
                    }

                    if (propertyValue != nil) {
                        [myObj setValue:propertyValue forKey:propertyName];
                    }
                }

            }
            else if ([propertyClassType isEqualToString:@"NSDictionary"] || [propertyClassType isEqualToString:@"NSMutableDictionary"]) {
                //字典类型   不考虑,一般不会用字典,用自定义model

            }
            else if ([propertyClassType isEqualToString:@"NSString"]) {
                //字符串类型
                if (propertyValue != nil) {
                    [myObj setValue:propertyValue forKey:propertyName];
                }
            }
            else {
                //自定义类型,循环调用,一直到不是自定义类型
                propertyValue = [NSClassFromString(propertyClassType) yj_initWithDictionary:propertyValue];
                if (propertyValue != nil) {
                    [myObj setValue:propertyValue forKey:propertyName];
                }
            }
        }
        else if ([propertyType isEqualToString:YJClassType_basic]) {
            //基本数据类型
            if ([propertyClassType isEqualToString:@"c"]) {
                //bool类型
                NSString *lowerValue = [propertyValue lowercaseString];
                if ([lowerValue isEqualToString:@"yes"] || [lowerValue isEqualToString:@"true"]) {
                    propertyValue = @(YES);
                } else if ([lowerValue isEqualToString:@"no"] || [lowerValue isEqualToString:@"false"]) {
                    propertyValue = @(NO);
                }
            }
            else {
                propertyValue = [[[NSNumberFormatter alloc] init] numberFromString:propertyValue];
            }

            if (propertyValue != nil) {
                [myObj setValue:propertyValue forKey:propertyName];
            }
        }
        else {
            //其他类型
        }
    }

    free(arrPropertys);

    return myObj;
}

4、字典中包含一些iOS不能用的字段

  • 有时候接口返回的数据中有id等iOS中和关键字重合的字段, 这个时候我们需要将id手动映射到模型中对应的属性中
  • 我们在刚刚创建的协议中在添加一个方法来处理
@protocol YJModelDicTransform 

@optional

/**
 *  数组中存储的类型
 *
 *  @return key --- 属性名,  value --- 数组中存储的类型
 */
+ (NSDictionary *)yj_objectClassInArray;

/**
 *  替换一些字段
 *
 *  @return key -- 模型中的字段, value --- 字典中的字段
 */
+ (NSDictionary *)yj_propertykeyReplacedWithValue;

@end
  • 在model中实现这个方法
+ (NSDictionary *)yj_propertykeyReplacedWithValue
{
    return @{@"_id":@"id"};
}
+ (instancetype)yj_initWithDictionary:(NSDictionary *)dic
{
    id myObj = [[self alloc] init];

    unsigned int outCount;

    //获取类中的所有成员属性
    objc_property_t *arrPropertys = class_copyPropertyList([self class], &outCount);

    for (NSInteger i = 0; i < outCount; i ++) {
        objc_property_t property = arrPropertys[i];

        //获取属性名字符串
        //model中的属性名
        NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
        //字典中的属性名
        NSString *newPropertyName;

        if ([self respondsToSelector:@selector(yj_propertykeyReplacedWithValue)]) {
            newPropertyName = [[self yj_propertykeyReplacedWithValue] objectForKey:propertyName];
        }
        if (!newPropertyName) {
            newPropertyName = propertyName;
        }

        NSLog(@"属性名:%@", propertyName);

        id propertyValue = dic[newPropertyName];
        if (propertyValue == nil) {
            continue;
        }

        //获取属性是什么类型的
        NSDictionary *dicPropertyType = [self propertyTypeFromProperty:property];
        NSString *propertyClassType = [dicPropertyType objectForKey:@"classType"];
        NSString *propertyType = [dicPropertyType objectForKey:@"type"];
        if ([propertyType isEqualToString:YJClassType_object]) {
            if ([propertyClassType isEqualToString:@"NSArray"] || [propertyClassType isEqualToString:@"NSMutableArray"]) {
                //数组类型
                if ([self respondsToSelector:@selector(yj_objectClassInArray)]) {
                    id propertyValueType = [[self yj_objectClassInArray] objectForKey:propertyName];
                    if ([propertyValueType isKindOfClass:[NSString class]]) {
                        propertyValue = [NSClassFromString(propertyValueType) yj_initWithArray:propertyValue];
                    }
                    else {
                        propertyValue = [propertyValueType yj_initWithArray:propertyValue];
                    }

                    if (propertyValue != nil) {
                        [myObj setValue:propertyValue forKey:propertyName];
                    }
                }

            }
            else if ([propertyClassType isEqualToString:@"NSDictionary"] || [propertyClassType isEqualToString:@"NSMutableDictionary"]) {
                //字典类型   不考虑,一般不会用字典,用自定义model

            }
            else if ([propertyClassType isEqualToString:@"NSString"]) {
                //字符串类型
                if (propertyValue != nil) {
                    [myObj setValue:propertyValue forKey:propertyName];
                }
            }
            else {
                //自定义类型
                propertyValue = [NSClassFromString(propertyClassType) yj_initWithDictionary:propertyValue];
                if (propertyValue != nil) {
                    [myObj setValue:propertyValue forKey:propertyName];
                }
            }
        }
        else if ([propertyType isEqualToString:YJClassType_basic]) {
            //基本数据类型
            if ([propertyClassType isEqualToString:@"c"]) {
                //bool类型
                NSString *lowerValue = [propertyValue lowercaseString];
                if ([lowerValue isEqualToString:@"yes"] || [lowerValue isEqualToString:@"true"]) {
                    propertyValue = @(YES);
                } else if ([lowerValue isEqualToString:@"no"] || [lowerValue isEqualToString:@"false"]) {
                    propertyValue = @(NO);
                }
            }
            else {
                propertyValue = [[[NSNumberFormatter alloc] init] numberFromString:propertyValue];
            }

            if (propertyValue != nil) {
                [myObj setValue:propertyValue forKey:propertyName];
            }
        }
        else {
            //其他类型
        }
    }

    free(arrPropertys);

    return myObj;
}
  • 控制器中
- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"字典转模型";

    NSDictionary *dicTest = @{@"id":@"121",
                              @"name":@"张三",
                              @"phone":@"110",
                              @"age":@"10",
                              @"user":@{@"userId":@"2"},
                              @"arrUsers":@[@{@"userId":@"2"},@{@"userId":@"2"},@{@"userId":@"2"}]};
    TestModel *model = [TestModel yj_initWithDictionary:dicTest];
    NSLog(@"model-----id:%@, name:%@, phone:%@, address:%@, age:%@, userId:%@, userName:%@", model._id, model.name, model.phone, model.address, @(model.age), model.user.userId, model.user.userName);
    [model.arrUsers enumerateObjectsUsingBlock:^(UserModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"arrUser----userId:%@", obj.userId);
    }];
}
  • 控制台打印

    2016-12-19 17:17:03.245 YJModelDicTransform[2099:158162] model-----id:121, name:张三, phone:110, address:(null), age:10, userId:2, userName:(null)
    2016-12-19 17:17:03.245 YJModelDicTransform[2099:158162] arrUser----userId:2
    2016-12-19 17:17:03.245 YJModelDicTransform[2099:158162] arrUser----userId:2
    2016-12-19 17:17:03.245 YJModelDicTransform[2099:158162] arrUser----userId:2

到此,基本完成了字典转模型的功能。接下来就是要在实际项目中多用,找出bug和不足点,继续完善它。

点击下载源代码