您的位置:首页 > 移动开发 > IOS开发

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

2016-03-22 17:20 337 查看
      说明: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属性名改成[b]productID
[/b]

 

[b]4.如何使用model类?     [b][b]控制器[/b][b]导入模型头文件.h。[/b]
在网络请求回来的数据方法中,这样调用  [/b][/b]

[b] MyMessageModel *model = [[MyMessageModel alloc] initWithDictionary:data];[/b]

[b]这样既可创建了一个数据模型。[/b]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: