1.封装数据模型可能遇到的情况
1)外界访问模型中没有的属性(需要添加防止崩溃代码)
2)数据模型中存在与关键字冲突的属性名(需要对属性名进行转换)
3)数据模型中又包含有别的数据模型时(需要对此类属性在整体kvc之后,进行单独设置)
2.一般思路
1)先根据后台提供的开发文档,设置属性值(必须通文档相同)与关键字,NSString 用copy;int 用assign关键字
2)提供一个初始化此类数据模型的类方法和对象方法
一般的命名如下:
+(instancetype)模型名(去掉前缀)WithDict:(NSDictionary *)dict;
- (instancetype)initWithDict:(NSDictionary *)dict;
3)实现提供的类方法和对象方法
+(instancetype)模型名(去掉前缀)WithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
- (instancetype)initWithDict:(NSDictionary *)dict
{
//一般构造方法,都是需要判断其父类方法是否返回真值
if (self = [super init]) {
// 1.注入所有属性
[self setValuesForKeysWithDictionary:dict];
// 2.特殊处理friends属性
NSMutableArray *friendArray = [NSMutableArray array];
for (NSDictionary *dict in self.friends) {
MJFriend *friend = [MJFriend friendWithDict:dict];
[friendArray addObject:friend];
}
self.friends = friendArray;
}
return self;
}
4).1中提到的一些优化
防止外界访问不存在的属性时崩溃
- (id) valueForUndefineKey:(NSString *)key
{
return nil;
}
为与关键字重复的成员变量进行转换
- (void)setValue:(id)value forUndefineKey:(NSString *)key
{
if([key isEqualtoString:@"id"])
{
_heroID = value;
}
}
3.关键代码


1 // 2 // MJFriendGroup.h 3 // 03-QQ好友列表 4 // 5 // Created by apple on 14-4-3. 6 // Copyright (c) 2014年 itcast. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 11 @interface MJFriendGroup : NSObject 12 @property (nonatomic, copy) NSString *name; 13 /** 14 * 数组中装的都是MJFriend模型 15 */ 16 @property (nonatomic, strong) NSArray *friends; 17 @property (nonatomic, assign) int online; 18 @property (nonatomic,copy) NSString * groupID; 19 20 /** 21 * 标识这组是否需要展开, YES : 展开 , NO : 关闭 22 */ 23 @property (nonatomic, assign, getter = isOpened) BOOL opened; 24 25 + (instancetype)groupWithDict:(NSDictionary *)dict; 26 - (instancetype)initWithDict:(NSDictionary *)dict; 27 @end


1 #import "MJFriendGroup.h" 2 #import "MJFriend.h" 3 4 @implementation MJFriendGroup 5 + (instancetype)groupWithDict:(NSDictionary *)dict 6 { 7 return [[self alloc] initWithDict:dict]; 8 } 9 10 - (instancetype)initWithDict:(NSDictionary *)dict 11 { 12 if (self = [super init]) { 13 // 1.注入所有属性 14 [self setValuesForKeysWithDictionary:dict]; 15 16 // 2.特殊处理friends属性 17 NSMutableArray *friendArray = [NSMutableArray array]; 18 for (NSDictionary *dict in self.friends) { 19 MJFriend *friend = [MJFriend friendWithDict:dict]; 20 [friendArray addObject:friend]; 21 } 22 self.friends = friendArray; 23 } 24 return self; 25 } 26 //防止外界访问不存在属性报错 27 - (id)valueForUndefinedKey:(NSString *)key 28 { 29 return nil; 30 } 31 32 - (void)setValue:(id)value forKey:(NSString *)key 33 { 34 if ([key isEqualToString:@"id"]) { 35 _groupID = value; 36 } 37 38 } 39 @end