runtime与字典转模型

作者: 小虎哥 | 来源:发表于2016-03-14 10:46 被阅读543次

设计模型

  • 模型属性,通常需要跟字典中的key一一对应,一个一个的生成模型属性,很慢
  • 我们提供一个字典分类,专门根据字典生成对应的属性字符串。
#import "NSDictionary+PropertyCode.h"

// isKindOfClass:判断是否是当前类或者它的子类

@implementation NSDictionary (PropertyCode)
- (void)createPropertyCode
{
    NSMutableString *strM = [NSMutableString string];
    /*
        解析字典,生成对应属性代码
        1.遍历字典,取出所有key,每个key对应一个属性代码
     
     */
    [self enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull value, BOOL * _Nonnull stop) {
        NSLog(@"%@ %@",key,[value class]);
        

        NSString *code = nil;
        if ([value isKindOfClass:[NSString class]]) {
            // NSString
            code = [NSString stringWithFormat:@"@property (nonatomic ,strong) NSString *%@;",key];
            
        } else if ([value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]){
            //    Bool
            code = [NSString stringWithFormat:@"@property (nonatomic ,assign) BOOL %@;",key];
        }else if ([value isKindOfClass:[NSNumber class]]){
            //    NSInteger
            code = [NSString stringWithFormat:@"@property (nonatomic ,assign) NSInteger %@;",key];
        }else if ([value isKindOfClass:[NSArray class]]){
            //    NSArray
            code = [NSString stringWithFormat:@"@property (nonatomic ,strong) NSArray *%@;",key];
        }else if ([value isKindOfClass:[NSDictionary class]]){
            //    NSDictionary
            code = [NSString stringWithFormat:@"@property (nonatomic ,strong) NSDictionary *%@;",key];
            
        }
        

         // 获取所有key
        [strM appendFormat:@"\n%@\n",code];
       
    }];
    
    NSLog(@"%@",strM);
    
}
@end

字典转模型

方式一:KVC

  • 弊端:必须保证,模型中的属性和字典中的key一一对应
  • 如果不一致,就会调用setValue:forUndefinedKey:报key
    找不到的错。
  • 解决:重写对象的setValue:forUndefinedKey: ,把系统的方法覆盖, 就能继续使用KVC,字典转模型了
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{

}

方式二:Runtime

  • 思路:利用运行时,遍历模型中所有属性,根据模型的属性名,去字典中查找key,取出对应的值,给模型的属性赋值。
  • 步骤:提供一个NSObject分类,专门字典转模型,以后所有模型都可以通过这个分类转。
    • 详细步骤:见代码
#import <Foundation/Foundation.h>

@protocol ModelDelegate <NSObject>

@optional
// 提供一个协议,只要准备这个协议的类,都能把数组中的字典转模型
、、用在三级数组转换
+ (NSDictionary *)arrayContainModelClass;

@end
@interface NSObject (Item)

// 字典转模型
+ (instancetype)objectWithDict:(NSDictionary *)dict;

@end
#import "NSObject+Item.h"

#import <objc/message.h>
/*
* 把字典中所有value给模型中属性赋值,
* KVC:遍历字典中所有key,去模型中查找
* Runtime:根据模型中属性名去字典中查找对应value,如果找到就给模型的属性赋值.
*/
@implementation NSObject (Item)
// 字典转模型
+ (instancetype)objectWithDict:(NSDictionary *)dict
{
    // 创建对应模型对象
    id objc = [[self alloc] init];
    
    
    unsigned int count = 0;
    
    // 1.获取成员属性数组
    Ivar *ivarList = class_copyIvarList(self, &count);
    
    // 2.遍历所有的成员属性名,一个一个去字典中取出对应的value给模型属性赋值
    for (int i = 0; i < count; i++) {
        
        // 2.1 获取成员属性
        Ivar ivar = ivarList[i];
        
        // 2.2 获取成员属性名 C -> OC 字符串
       NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];
        
        // 2.3 _成员属性名 => 字典key
        NSString *key = [ivarName substringFromIndex:1];
        
        // 2.4 去字典中取出对应value给模型属性赋值
        id value = dict[key];
        
        
        // 获取成员属性类型
        NSString *ivarType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
        
        // 二级转换,字典中还有字典,也需要把对应字典转换成模型
        //
        // 判断下value,是不是字典
        if ([value isKindOfClass:[NSDictionary class]] && ![ivarType containsString:@"NS"]) { //  是字典对象,并且属性名对应类型是自定义类型
            // user User
           
            // 处理类型字符串 @\"User\" -> User
            ivarType = [ivarType stringByReplacingOccurrencesOfString:@"@" withString:@""];
            ivarType = [ivarType stringByReplacingOccurrencesOfString:@"\"" withString:@""];
            // 自定义对象,并且值是字典
            // value:user字典 -> User模型
            // 获取模型(user)类对象
            Class modalClass = NSClassFromString(ivarType);
            
            // 字典转模型
            if (modalClass) {
                // 字典转模型 user
                value = [modalClass objectWithDict:value];
            }
            
            // 字典,user
//            NSLog(@"%@",key);
        }
      
        // 三级转换:NSArray中也是字典,把数组中的字典转换成模型.
        // 判断值是否是数组
        if ([value isKindOfClass:[NSArray class]]) {
            // 判断对应类有没有实现字典数组转模型数组的协议
            if ([self respondsToSelector:@selector(arrayContainModelClass)]) {
                
                // 转换成id类型,就能调用任何对象的方法
                id idSelf = self;
                
                // 获取数组中字典对应的模型
                NSString *type =  [idSelf arrayContainModelClass][key];
                
                // 生成模型
                Class classModel = NSClassFromString(type);
                NSMutableArray *arrM = [NSMutableArray array];
                // 遍历字典数组,生成模型数组
                for (NSDictionary *dict in value) {
                    // 字典转模型
                    id model =  [classModel objectWithDict:dict];
                    [arrM addObject:model];
                }
                
                // 把模型数组赋值给value
                value = arrM;
                
            }
        }

        // 2.5 KVC字典转模型
        if (value) {
            
            [objc setValue:value forKey:key];
        }
    }
    

    // 返回对象
    return objc;
    
}
@end
  • 模型代码
#import <Foundation/Foundation.h>
#import "NSObject+Item.h"
@class User;
@interface Status : NSObject <ModelDelegate>

@property (nonatomic, strong) NSString *source;

@property (nonatomic, assign) int reposts_count;

@property (nonatomic, strong) NSArray *pic_urls;

@property (nonatomic, strong) NSString *created_at;

@property (nonatomic, assign) int attitudes_count;

@property (nonatomic, strong) NSString *idstr;

@property (nonatomic, strong) NSString *text;

@property (nonatomic, assign) int comments_count;

@property (nonatomic, strong) User *user;

@end

#import "Status.h"

@implementation Status
+ (NSDictionary *)arrayContainModelClass
{
    return @{@"pic_urls" : @"Picture"};
}

@end

相关文章

  • runtime与字典转模型

    设计模型 模型属性,通常需要跟字典中的key一一对应,一个一个的生成模型属性,很慢 我们提供一个字典分类,专门根据...

  • runtime -- 实现字典转模型

    runtime与KVC字典转模型的区别:1.KVC:遍历字典中所有的key,去模型中查找有没有对应的属性名。2.r...

  • runtime字典转模型

    KVC:遍历字典中所有key,去模型中找有没有对应的属性名; Student *stu = [[Studental...

  • 字典转模型(runtime)

    接口返回的key转成属性名 model中嵌套子model 字典转模型

  • runtime字典转模型

    KVC实现字典转模型 模型类Status 其中,模型中的属性都是我通过上篇介绍的自动获取模型属性的方式来获得的外部...

  • Runtime字典转模型

    用一个分类实现字典转模型,分类头文件如下: 如果模型的属性有字典数组,想要将该字典数组转换成模型数组,那么在该模型...

  • iOS开发 runtime应用

    1.runtime的作用 字典转模型 动态修改成员变量 方法交换 给分类添加属性 2.字典转模型 原文参考链接:h...

  • runtime运行时之字典模型互转(二)

    上次介绍了runtime自动归档,这次我们来看一下非常常用的-字典转模型/模型转字典。很多朋友都会用到MJExte...

  • ios runtime 实现json转模型

    runtime 字典转模型,主要是利用runtime的class_copyIvarList方法来获取到类中的所有的...

  • 14-Swift中字典转模型

    字典转模型(初始化时传入字典) 字典转模型(利用KVC转化) 一、 普通的字典转模型: 二、利用KVC字典转模型:

网友评论

本文标题:runtime与字典转模型

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