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
  • 相关阅读:
    MySQL索引原理及慢查询优化
    MySQL单表百万数据记录分页性能优化
    linux下crontab命令的使用
    php递归读取目录
    php实现函数重载
    php数组常见的几种遍历方法
    ArtTemplate 使用笔记
    打算换工作的伙伴们,快来看啦,各种职位,随便挑咯...
    看看国外的javascript题目,你能全部做对吗?(分享)
    逛园子,看到个练习题,小试了一把(淘宝ued的两道小题)
  • 原文地址:https://www.cnblogs.com/GeekStar/p/4349667.html
Copyright © 2011-2022 走看看