標籤: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字典轉模型