iOS 开发之 KVC - setValuesForKeysWithDictionary 解析神器
来源:互联网 发布:腊肠犬 知乎 编辑:程序博客网 时间:2024/05/17 19:58
转载地址: http://blog.csdn.net/hdfqq188816190/article/details/48679909
从字典映射到一个对象,这是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:,然后实现以下替换,即可.
- iOS 开发之 KVC - setValuesForKeysWithDictionary 解析神器
- iOS学习之KVC中setValuesForKeysWithDictionary:
- iOS KVC setValuesForKeysWithDictionary的使用
- iOS开发之KVO与KVC解析与实战
- iOS开发之KVC、KVO
- iOS开发之KVC/KVO
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:详解
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary
- ZOJ 3936 Apples and Ideas(水题)
- Android中实时获取音量分贝值详解
- Java_语言基础
- LeetCode 343: Integer Break 题解
- OpenGL ES着色器语言之内建函数(官方文档第八章)
- iOS 开发之 KVC - setValuesForKeysWithDictionary 解析神器
- linux 内核内存分配
- 微信开发之本地开发环境的部署;本地当服务器!实时调试;
- 解决NameNode配置HA后Hive路径不正确的问题
- Python实践课-点球大战
- json字符串与json对象的区别
- 如何选择 compileSdkVersion, minSdkVersion 和 targetSdkVersion
- 【CodeForces 397A 】On Segment's Own Points(水题)
- hdu 2151