說明:model類模板已默認過濾null值,附加特殊情況的關鍵字ID名的沖突(需手動去掉注釋代碼)。MyMessageModel為示例的名字。可以自己隨便起。
1.自己創建一個繼承與NSObject的類,用於當model數據模型用。然后在.h文件中根據接口文檔或者json返回數據的添加相應屬性。
並復制以下model類模板代碼.h文件的- (instancetype)initWithDictionary:(NSDictionary *)dictionary;方法到自己創建的數據模型類.h中。
2.在自己的數據模型類.m文件中,復制以下model模板類.m中代碼到自己創建的類.m中。
model類.h文件
1 #import <Foundation/Foundation.h> 2 3 @interface MyMessageModel : NSObject 4 5 6 // 示例屬性名,根據后台接口返回的數據自己copy到此處 7 8 @property (nonatomic, strong) NSString *namet; 9 10 /** 11 * Init the model with dictionary 12 * 13 * @param dictionary dictionary 14 * 15 * @return model 16 */ 17 - (instancetype)initWithDictionary:(NSDictionary *)dictionary; 18 19 @end
modell類.m文件
1 #import "MyMessageModel.h" 2 3 @implementation MyMessageModel 4 5 - (void)setValue:(id)value forUndefinedKey:(NSString *)key { 6 7 /* [Example] change property id to productID 8 * 9 * if([key isEqualToString:@"id"]) { 10 * 11 * self.productID = value; 12 * return; 13 * } 14 */ 15 16 // show undefined key 17 // NSLog(@"%@.h have undefined key '%@', the key's type is '%@'.", NSStringFromClass([self class]), key, [value class]); 18 } 19 20 - (void)setValue:(id)value forKey:(NSString *)key { 21 22 // ignore null value 23 if ([value isKindOfClass:[NSNull class]]) { 24 25 return; 26 } 27 28 [super setValue:value forKey:key]; 29 } 30 31 - (instancetype)initWithDictionary:(NSDictionary *)dictionary { 32 33 if ([dictionary isKindOfClass:[NSDictionary class]]) { 34 35 if (self = [super init]) { 36 37 [self setValuesForKeysWithDictionary:dictionary]; 38 } 39 } 40 41 return self; 42 } 43 44 @end
3.對於極少情況下遇到的接口返回json數據帶ID的參數和系統ID關鍵字沖突的解決。
打開.m中
/* [Example] change property id to productID
if([key isEqualToString:@"id"])
{
self.productID = value;
return; }
*/ 打開這行的注釋。將.h中沖突的ID屬性名改成productID
4.如何使用model類? 控制器導入模型頭文件.h。 在網絡請求回來的數據方法中,這樣調用
MyMessageModel *model = [[MyMessageModel alloc] initWithDictionary:data];
這樣既可創建了一個數據模型。
