runtime -- 实现字典转模型

作者: 我的梦想之路 | 来源:发表于2016-06-12 22:12 被阅读279次

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

    #依旧是NSObjcet的model分类
    //字典转模型 -- runtime 实现
    #import <Foundation/Foundation.h>
    #import <objc/message.h>
    
    @interface NSObject (Model)
    + (instancetype)modelWithDict:(NSDictionary *)dict;
    @end
    
    # .m文件中
    + (instancetype)modelWithDict:(NSDictionary *)dict{
    
      // 创建对应类的对象
      id objc =[[self alloc] init];
    
    
    /**
    runtime:遍历模型中的属性名。去字典中查找。
    属性定义在类,类里面有个属性列表(即为数组)
    */
    # 方法名:class_copyIvarList(<#__unsafe_unretained Class cls#>, <#unsigned int *outCount#>) 
        // 遍历模型所有属性名
      #1. ivar : 成员属性(成员属性为带_name,而name为属性,属性与成员属性不一样。)
      #2. class_copyIvarList:把成员属性列表复制一份给你
      #3. cmd + 点击 查看方法返回一个Ivar *(表示指向一个ivar数组的指针)
    
      #4.class:获取哪个类的成员属性列表
      #5.count : 成员属性总数
    unsigned int count = 0;
    Ivar *ivarList = class_copyIvarList(self, &count);  
    
    // 遍历
      for (int i = 0; i< count; i++){
        Ivar ivar = ivarList[i];
        // 获取成员名(获取到的是C语言类型,需要转换为OC字符串)
        NSString *propertyName = [NSString stringWithUTF8String:ivar_getName(ivar)];
      
        // 成员属性类型
        NSString *propertyType = [NSString stringWithUTF8String: ivar_getTypeEncoding(ivar)];
    
        // 首先获取key(根据你的propertyName 截取字符串)
         NSString *key = [propertyName substringFromIndex:1];
        // 获取字典的value
        id value = dict[key];
    
         // 给模型的属性赋值
        // value : 字典的值
        // key : 属性名
        if (value){  // 这里是因为KVC赋值,不能为空
           [objc setValue:value forKey:key];
    
        }
       NSLog(@"%@  %@",propertyType,propertyName);
      }
    
    NSLog(@"%zd",count); // 这里会输出self中成员属性的总数
     return objc;
    }
    
    #viewController中
    NSMutableArray *models = [NSMutableArray array];
    for (NSDictionary *dict in dictArr){
          // 字典转模型(别忘记导入model类)
        Model *modle = [Model modelWithDict:dict];
        
       [models addOBject:model];
    }
    NSLog(@"%@",models);
    

    这里就完结了,有点难理解。特别是Ivar,是runtime的东西。

    记住就好了。因为我也还不是很清楚。晚安,好梦

    相关文章

      网友评论

        本文标题:runtime -- 实现字典转模型

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