iOS開發——model類模板(過濾null和ID)
阿新 • • 發佈:2019-01-10
說明: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 model16 */ 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];
這樣既可建立了一個數據模型。