ios字典转模型
标签:ios 字典转模型
    
 一、在模型类中自定义方法来实现,注意:属性名称和字典里面的KEY要和实际数据的属性一样
  a、在模型类中的实现
123456789101112131415161718192021222324252627282930    // 模型类 .h文件       @interface Person: NSObject       @property (nonatomic,copy) NSString *name;   @property (nonatomic,assign) UIInteger age;       // 自定义这个方法        - (instancetype)initWithDict:(NSDictionary *)dict;     + (instancetype)personWithDict:(NSDictionary *)dict;         @end     // 模型类 .m文件实现   - (instancetype)initWithDict:(NSDictionary *)dict {        if (self = [super init]){                           self.name = dict[@"name"];              self.age = dict[@"age"];          }                   return self; }  + (instancetype)personWithDict:(NSDictionary *)dict {        return [ [self alloc] initWithDict:dict];  }    
 b、在获取模型数据类中的实现
12     Person *p = [Person alloc] initWithDict:dict];(这里直接字典转模型) // Person *p = [Person personWithDict:dict];    
二、直接用KVC实现,注意模型属性要和数据的实际属性相同,不然用KVC方法会报错
  a、在模型类中的实现
1234567891011121314151617181920212223242526272829303132    // 模型类 .h文件       @interface Person: NSObject       @property (nonatomic,copy) NSString *name;   @property (nonatomic,assign) UIInteger age;       // 自定义这个方法    - (instancetype)initWithDict:(NSDictionary *)dict; + (instancetype)personWithDict:(NSDictionary *)dict;     @end    // 模型类 .m文件实现   - (instancetype)initWithDict:(NSDictionary *)dict {        if (self = [super init]){                          // self.name = dict[@"name"];            //  self.age = dict[@"age"];                            [self setValuesForKeysWithDictionary:dict];  (这里实现)     }                   return self; }  + (instancetype)personWithDict:(NSDictionary *)dict {        return [ [self alloc] initWithDict:dict];  }    
b、在获取模型数据类中的实现
12    1  Person *p = [Person alloc] initWithDict:dict];(这里直接字典转模型)2  // Person *p = [Person personWithDict:dict];    
三、利用封装好的第三方框架实现
  如: MJExtension  具体实现看github的介绍