setValuesForKeysWithDictionary
来源:互联网 发布:数据铭品 编辑:程序博客网 时间:2024/06/06 16:33
[转]KVC中setValuesForKeysWithDictionary:
http://m.blog.csdn.net/blog/dragonu013368288/23887063#
2014-4-17阅读203 评论0
从字典映射到一个对象,这是KVC中的一个方法所提供的,这个方法就是 setValuesForKeysWithDictionary: ,非常好用,不需要你来一一的给对象赋值而直接从字典初始化即可,但用的不好会经常崩溃,本教程就来讨论这些使用的细节.
我建立lol的模型
#import <Foundation/Foundation.h>@interface HeroModel : NSObject@property (nonatomic,copy) NSString *name;@property (nonatomic,copy) NSString *intro;@property (nonatomic,copy) NSString *icon;- (instancetype)initWithDict:(NSDictionary *)dict;+ (instancetype)heroWithDict:(NSDictionary *)dict;@end
#import "HeroModel.h"@implementation HeroModel- (instancetype)initWithDict:(NSDictionary *)dict{ if(self = [super init]){// self.icon = [dict[@"icon"] copy];// self.name = [dict[@"name"] copy];// self.intro = [dict[@"intro"] copy]; //苯方法 [self setValuesForKeysWithDictionary:dict]; } return self;}+ (instancetype)heroWithDict:(NSDictionary *)dict{ return [[self alloc] initWithDict:dict];}@end
首先,先初始化一个字典,如下所示:
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys: @"Y.X.", @"name", @"26", @"age", @"海淀区", @"address", nil];
创建PersonInfoModel,代码如下所示
import
import “PersonInfoModel.h”
@implementation PersonInfoModel
@end
测试后打印信息如下:
以上是很标准的使用方法,我们再在属性中添加 other,如下图所示:
也没有出错,可以正常使用,也就是说用字典初始化对象时,只要对象中都包含了这些键值,是可以正常初始化的,我们再在字典中添加一个键值对,如下图所示:
直接导致程序崩溃,因为该对象中没有 sex 这个属性,解决方法就是,实现一个方法setValue:forUndefinedKey:,如下图所示:
这样子就会过滤掉给不存在的键值赋值,如果有个属性是id,而id本身就是系统自身关键字,不能够当做属性使用,怎么办?
结论:
setValue:forUndefinedKey:这个方法是关键,只有存在这个方法后,才可以过滤掉不存在的键值对而防止崩溃,同时,setValue:forUndefinedKey:这个方法中还可以改变系统的敏感字,或者,你手动的映射key值不同的值,随你自己喜欢.
0 0
- setValuesForKeysWithDictionary
- iOS setValuesForKeysWithDictionary
- setValuesForKeysWithDictionary 使用方法
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- 自定义实现setValuesForKeysWithDictionary
- setValuesForKeysWithDictionary的妙用
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:详解
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary
- setValuesForKeysWithDictionary崩溃问题
- 编程常用英语单词(一)
- JS之——比较字符串大小(插曲)
- 狂刷Android范例之1:ReadAsset
- 创建ajax对象
- 使用pyinstaller打包python为exe文件
- setValuesForKeysWithDictionary
- HDU 1058 Humble Numbers--DP--(计数器技巧)
- Oracle编译器警告
- mysql旧表去重数据导入新表且赋予主键id新值
- 软件开发团队阶段
- 编程常用英语单词(二)
- MyEclipse设置JVM内存大小
- java基础集合数组间的转换(java集合五)
- 如何解决 Intent 调用缓冲数据问题