ios-教你一步一步實現自己的字典轉模型庫

feiji.jpg

前言

我們在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 <NSObject>

@optional

/**
 *  數組中存儲的類型
 *
 *  @return key --- 屬性名,  value --- 數組中存儲的類型
 */
+ (NSDictionary *)yj_objectClassInArray;

@end

@interface NSObject (YJModelDicTransform)<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 <NSObject>

@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和不足點,繼續完善它。

點擊下載源代碼

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容