KVC中setValuesForKeysWithDictionary:
来源:互联网 发布:在淘宝店铺被限制购买 编辑:程序博客网 时间:2024/05/22 17:18
从字典映射到一个对象,这是KVC中的一个方法所提供的,这个方法就是 setValuesForKeysWithDictionary: ,非常好用,不需要你来一一的给对象赋值而直接从字典初始化即可,但用的不好会经常崩溃,本教程就来讨论这些使用的细节.
首先,先初始化一个字典,如下所示:
-------------------------------------------------------------------------------------
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
@"Y.X.", @"name",
@"26", @"age",
@"海淀区", @"address", nil];
-------------------------------------------------------------------------------------
创建PersonInfoModel,代码如下所示
-------------------------------------------------------------------------------------
#import <Foundation/Foundation.h>
@interface PersonInfoModel : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *age;
@property (nonatomic, strong) NSString *address;
@end
-------------------------------------------------------------------------------------
#import "PersonInfoModel.h"
@implementation PersonInfoModel
@end
-------------------------------------------------------------------------------------
测试后打印信息如下:
以上是很标准的使用方法,我们再在属性中添加 other,如下图所示:
也没有出错,可以正常使用,也就是说用字典初始化对象时,只要对象中都包含了这些键值,是可以正常初始化的,我们再在字典中添加一个键值对,如下图所示:
直接导致程序崩溃,因为该对象中没有 sex 这个属性,解决方法就是,实现一个方法setValue:forUndefinedKey:,如下图所示:
这样子就会过滤掉给不存在的键值赋值,如果有个属性是id,而id本身就是系统自身关键字,不能够当做属性使用,怎么办?
结论:
setValue:forUndefinedKey:这个方法是关键,只有存在这个方法后,才可以过滤掉不存在的键值对而防止崩溃,同时,setValue:forUndefinedKey:这个方法中还可以改变系统的敏感字,或者,你手动的映射key值不同的值,随你自己喜欢.
附录:
哥教你一个一劳永逸的方式来处理这种映射到错误键值而导致崩溃的问题,首先,你先继承至 NSObject 类,实现方法setValue:forUndefinedKey:
然后,你新建一个model,继承至 YXModel 类,如下图所示:
然后使用,请注意,其有一个值为null,因为没有这个myID的键值嘛.
解决方法,重载父类的setValue:forUndefinedKey:,然后实现以下替换,即可.
转载来自:http://www.cnblogs.com/YouXianMing/p/3641304.html
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:详解
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary
- KVC中setValuesForKeysWithDictionary用法
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary
- KVC中setValuesForKeysWithDictionary:
- db2自增主键
- error LNK2005: 已经在xxx.obj中定义
- 11-13款卡宴改TURBO套件
- jquery日历datepicker的使用方法
- OGNL表达式
- KVC中setValuesForKeysWithDictionary:
- 给SQLite数据库加密
- 安卓安全新机Blackphone,3周后出货
- Android回顾之如何实现android和服务器长连接呢?推送消息的原理
- cocos2dx三种定时器的使用以及停止
- java 排序算法
- 黑马程序员_交通灯系统
- Axis2服务端用户名和密码校验authentication代码
- Android ActionBar详解