iOS学习之KVC中setValuesForKeysWithDictionary:
来源:互联网 发布:java类加载器哪三种 编辑:程序博客网 时间:2024/05/19 22:02
从字典映射到一个对象,这是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值不同的值,随你自己喜欢.
0 0
- iOS学习之KVC中setValuesForKeysWithDictionary:
- iOS 开发之 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:
- 喷水装置(二)(最小线段覆盖)
- Android 百度地图开发(一)如何调用百度地图接口和在项目中显示百度地图以及实现定位
- 事务隔离级别、事务传播属性、事务锁
- 网络请求之——————post
- PS AD系列命令之new-aduser 新建用户命令!
- iOS学习之KVC中setValuesForKeysWithDictionary:
- [leetcode] 179 Largest Number
- HDU 2602 Bone Collector 【01背包】
- 【springmvc+mybatis项目实战】杰信商贸-11.购销合同业务
- SubShader中Pass
- struts2常用标签总结
- SpringMVC+mybatis+spring整合教程
- 华为软件测试 字符串最后一个单词的长度
- 是时候该总结下自己工作常用的linux命令了