ios字典轉模型

    

 一、在模型類中自定義方法來實現注意:屬性名稱和字典裏面的KEY要和實際數據的屬性一樣

  a、在模型類中的實現

// 模型類 .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、在獲取模型數據類中的實現

 Person *p = [Person alloc] initWithDict:dict];(這裏直接字典轉模型)
 // Person *p = [Person personWithDict:dict];


二、直接用KVC實現,注意模型屬性要和數據的實際屬性相同,不然用KVC方法會報錯

  a、在模型類中的實現

// 模型類 .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、在獲取模型數據類中的實現

1  Person *p = [Person alloc] initWithDict:dict];(這裏直接字典轉模型)
2  // Person *p = [Person personWithDict:dict];


三、利用封裝好的第三方框架實現

  如: MJExtension  具體實現看github的介紹

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章