zoukankan      html  css  js  c++  java
  • iOS 字典转模型

      一、在模型类中自定义方法来实现注意:属性名称和字典里面的KEY要和实际数据的属性一样

      a、在模型类中的实现

     1    // 模型类 .h文件
     2    
     3    @interface Person: NSObject
     4    
     5    @property (nonatomic,copy) NSString *name;
     6    @property (nonatomic,assign) UIInteger age;
     7    
     8    // 自定义这个方法
     9   
    10      - (instancetype)initWithDict:(NSDictionary *)dict;
    11      + (instancetype)personWithDict:(NSDictionary *)dict;
    12     
    13     @end   
    14 
    15  // 模型类 .m文件实现
    16  
    17  - (instancetype)initWithDict:(NSDictionary *)dict
    18  {
    19         if (self = [super init]){
    20             
    21               self.name = dict[@"name"];
    22               self.age = dict[@"age"];     
    23      }          
    24          return self;
    25  }
    26 
    27  + (instancetype)personWithDict:(NSDictionary *)dict
    28  {
    29         return [ [self alloc] initWithDict:dict]; 
    30  } 

      b、在获取模型数据类中的实现

    1 Person *p = [Person alloc] initWithDict:dict];(这里直接字典转模型)
    2 // Person *p = [Person personWithDict:dict];

      二、直接用KVC实现,跟上面的差不多

      a、在模型类中的实现

     1    // 模型类 .h文件
     2    
     3    @interface Person: NSObject
     4    
     5    @property (nonatomic,copy) NSString *name;
     6    @property (nonatomic,assign) UIInteger age;
     7    
     8    // 自定义这个方法
     9   
    10  - (instancetype)initWithDict:(NSDictionary *)dict;
    11  + (instancetype)personWithDict:(NSDictionary *)dict;
    12 
    13     @end  
    14 
    15  // 模型类 .m文件实现
    16  
    17  - (instancetype)initWithDict:(NSDictionary *)dict
    18  {
    19         if (self = [super init]){
    20             
    21              // self.name = dict[@"name"];
    22             //  self.age = dict[@"age"];    
    23            
    24             [self setValuesForKeysWithDictionary:dict];  (这里实现)
    25      }          
    26          return self;
    27  }
    28 
    29  + (instancetype)personWithDict:(NSDictionary *)dict
    30  {
    31         return [ [self alloc] initWithDict:dict]; 
    32  }    

      b、在获取模型数据类中的实现

    1  Person *p = [Person alloc] initWithDict:dict];(这里直接字典转模型)
    2  // Person *p = [Person personWithDict:dict];

      三、利用封装好的第三方框架实现

      如: MJExtension  具体实现看github的介绍

    欢迎加QQ群交流: iOS: 279096195 React Native: 482205185
  • 相关阅读:
    计算两个字符串的最大公共字串的长度,字符不区分大小写
    任何一个整数m的立方都可以写成m个连续奇数之和。
    求一个byte数字对应的二进制数字中1的最大连续数
    Elasticsearch的过滤查询
    如何在Elasticsearch中安装中文分词器(IK+pinyin)
    使用Linux的alternatives命令替换选择软件的版本
    PHP如何与搜索引擎Elasticsearch交互?
    如何安装搜索引擎Elasticsearch?
    如何修改MAC自带的PHP的版本?
    程序员技能图谱
  • 原文地址:https://www.cnblogs.com/GeekStar/p/4349667.html
Copyright © 2011-2022 走看看