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的介绍