1. 新建模型
@interface Student : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *age;
@property (nonatomic, copy) NSString *address;
@property (nonatomic, copy) NSString *sex;
-(instancetype)initWithDict:(NSDictionary *)dict;
+(instancetype)studentWithDict:(NSDictionary *)dict;
@end
实现字典转模型方法
-(instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
+(instancetype)studentWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
创建模型对象
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"X.E",@"name"
@"26", @"age"
@"Male", @"sex",
@"textalignment", @"id",
nil];
Student *stu = [Student studentWithDict:dict];
解决问题
上述的代码中,创建的dict中有一个key为id。id是系统保留字段,在Model对象中不可能创建变量名为id,所以上述的代码可定会崩溃。为了不让app崩溃必须要在模型中实现方法如下方法:
-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
if ([key isEqualToString:@"id"]) {
self.address = value;
}
}
所有的undefinedKey都会调用这个方法,在这个方法中可以为未定义的key做一些处理,或者完全不做处理。