(iOS开发)Model中数据多怎么办,JSON中数据多,种类多的解析Model

来源:互联网 发布:淘宝网购物女裤 编辑:程序博客网 时间:2024/05/29 09:37
//model是自己的类型  ,dic是json中所需要解析出来的字典[model setValuesForKeysWithDictionary:dic];//1、如果model里面的有不存在于dic中的元素会怎样?//在Model文件中添加一行@property (nonatomic,copy)NSString *other;//并输出得时候输出NSLog(@"test.other=%@",test.other);//2.如果dic里面的有不存在于model中的元素会怎样?//在Model文件中删除一行@property (nonatomic,copy) NSString* age;//在删除对应得输出后运行。//糟了!通过了编译,但是运行时报错!Terminating app due to uncaught exception 'NSUnknownKeyException',reason: '[<PersonModel 0x7fd731517910> setValue:forUndefinedKey:]:this class is not key value coding-compliant for the key age.'    //因为在model中,没有对应的age属性,所以导致了程序崩溃。        //解决方式就是实现一个方法setValue:forUndefinedKey: 这个方法能过滤掉不存在的键值。        //在model中添加。    //h文件中添加:        -(void)setValue:(id)value forUndefinedKey:(NSString *)key;//并需要在m文件中实现:-(void)setValue:(id)value forUndefinedKey:(NSString *)key{    }//3.如果dic中的key与model中的变量名字不同,应该怎么赋值?//从前面我们可以知道,dic中key赋值给model中与key同名的属性。//那么如果dic中得key值为 username,model中的名字为name,又或是dic中的key值为ID,INT 等关键字,应该怎么变化。//答案也是从setValue:forUndefinedKey方法入手。//首先我们把dic的值改变:NSDictionary *dic = @{@"username":@"张三",@"sex":@"男",@"id":@"22"};//model中的属性:@property (nonatomic,copy)NSString *name;@property (nonatomic,copy)NSString *sex;@property (nonatomic,copy) NSString* age;//完善model中的setValue:forUndefinedKey方法-(void)setValue:(id)value forUndefinedKey:(NSString *)key{    if([key isEqualToString:@"id"])    {        self.age=value;    }    if([key isEqualToString:@"username"])    {        self.name=value;    }}//运行后结果:2015-10-19 14:30:11.241setValuesForKeysWithDictionary[10289:956012] test.name=张三2015-10-19 14:30:11.242setValuesForKeysWithDictionary[10289:956012] test.sex=男2015-10-19 14:30:11.242setValuesForKeysWithDictionary[10289:956012] test.age=22//正常输出!

转载自http://www.jianshu.com/p/870eb4b4170a


0 0
原创粉丝点击