iOS开发——model类模板(过滤null和ID)

      说明: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];

这样既可创建了一个数据模型。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值