ios字典轉模型

來源:互聯網
上載者:User

標籤:ios字典轉模型

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


本文出自 “技術部落格” 部落格,請務必保留此出處http://9077272.blog.51cto.com/9067272/1633794

ios字典轉模型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.