字典的快速赋值 setValuesForKeysWithDictionary

字数918 阅读6604 评论6 喜欢32

前言

在学习解析数据的时候,我们经常是这么写的:
PersonModel.h文件中

    @property (nonatomic,copy)NSString *name;
@property (nonatomic,copy)NSString *sex;
@property (nonatomic,copy)NSString *age;

字典:

     NSDictionary *dic = @{@"name":@"张三",@"sex":@"男",@"age":@"22"};

赋值:

     PersonModel *test=[[PersonModel alloc]init];
test.name=dic[@"name"];
test.sex=dic[@"sex"];
test.age=dic[@"age"];

输出:

        NSLog(@"test.name=%@",test.name);
NSLog(@"test.sex=%@",test.sex);
NSLog(@"test.age=%@",test.age);

输出结果:

2015-10-19 13:31:25.478
setValuesForKeysWithDictionary[9676:913009] test.name=张三
2015-10-19 13:31:25.478
setValuesForKeysWithDictionary[9676:913009] test.sex=男
2015-10-19 13:31:25.478
setValuesForKeysWithDictionary[9676:913009] test.age=22

看上去很有条理,按部就班,但是一旦数据多了起来,却会非常繁琐,所以这次我会介绍一个相对轻松的方法setValuesForKeysWithDictionary。


简单使用

如果用setValuesForKeysWithDictionary这个方法会怎样?
将赋值过程

  test.name=dic[@"name"];
test.sex=dic[@"sex"];
test.age=dic[@"age"];

替换为一句话

    [test setValuesForKeysWithDictionary:dic];

输出结果一模一样,是不是简单又方便?


深入的问题

  1. 如果model里面的有不存在于dic中的元素会怎样?

在Model文件中添加一行

    @property (nonatomic,copy)NSString *other;

并输出得时候输出

     NSLog(@"test.other=%@",test.other);

输出结果:

2015-10-19 13:49:25.955
setValuesForKeysWithDictionary[9964:928391] test.name=张三
2015-10-19 13:49:25.956
setValuesForKeysWithDictionary[9964:928391] test.sex=男
2015-10-19 13:49:25.956
setValuesForKeysWithDictionary[9964:928391] test.age=22
2015-10-19 13:49:25.956
setValuesForKeysWithDictionary[9964:928391] test.other=(null)

显而易见,dic中得值可以完全赋值给model,而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{

    }

对,并不需要在方法中写任何内容。
现在来运行一下。
输出结果:

2015-10-19 13:55:55.390
setValuesForKeysWithDictionary[10082:937173] test.name=张三
2015-10-19 13:55:55.391
setValuesForKeysWithDictionary[10082:937173] test.sex=男

成功运行!


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.241
setValuesForKeysWithDictionary[10289:956012] test.name=张三
2015-10-19 14:30:11.242
setValuesForKeysWithDictionary[10289:956012] test.sex=男
2015-10-19 14:30:11.242
setValuesForKeysWithDictionary[10289:956012] test.age=22

正常输出!

setValuesForKeysWithDictionary 的用法的更多相关文章

  1. KVC的用法

    示例1:基本赋值取值 @interface Book : NSObject {     NString *name;}@end #import "Book.h"@implement ...

  2. EditText 基本用法

    title: EditText 基本用法 tags: EditText,编辑框,输入框 --- EditText介绍: EditText 在开发中也是经常用到的控件,也是一个比较必要的组件,可以说它是 ...

  3. jquery插件的用法之cookie 插件

    一.使用cookie 插件 插件官方网站下载地址:http://plugins.jquery.com/cookie/ cookie 插件的用法比较简单,直接粘贴下面代码示例: //生成一个cookie ...

  4. Java中的Socket的用法

                                   Java中的Socket的用法 Java中的Socket分为普通的Socket和NioSocket. 普通Socket的用法 Java中的 ...

  5. [转载]C#中MessageBox.Show用法以及VB.NET中MsgBox用法

    一.C#中MessageBox.Show用法 MessageBox.Show (String) 显示具有指定文本的消息框. 由 .NET Compact Framework 支持. MessageBo ...

  6. python enumerate 用法

    A new built-in function, enumerate() , will make certain loops a bit clearer. enumerate(thing) , whe ...

  7. [转载]Jquery中$.get(),$.post(),$.ajax(),$.getJSON()的用法总结

    本文对Jquery中$.get(),$.post(),$.ajax(),$.getJSON()的用法进行了详细的总结,需要的朋友可以参考下,希望对大家有所帮助. 详细解读Jquery各Ajax函数: ...

  8. 【JavaScript】innerHTML、innerText和outerHTML的用法区别

    用法: <div id="test">   <span style="color:red">test1</span> tes ...

  9. chattr用法

    [root@localhost tmp]# umask 0022 一.chattr用法 1.创建空文件attrtest,然后删除,提示无法删除,因为有隐藏文件 [root@localhost tmp] ...

随机推荐

  1. OpenGL学习笔记4——模型视图变换

    以日月地为例的一个模型视图变换.绕了比较多的弯路,下面是几个注意点总结. 注意点: 1.GL函数对模型的操作是基于当前局部坐标系,即模型坐标系而非世界坐标系,二者只在第一次初始化完毕之后才重合: 2. ...

  2. Genymotion出现virtualbox cannot start the virtual device错误

    选择你要启动的device右侧的设置 打开如下界面 将Processor设置为1 (默认为4)

  3. js获取项目根目录的方法

    getRootPath = function(){ //获取当前网址,如: http://localhost:8080/ems/Pages/Basic/Person.jsp var curWwwPat ...

  4. 英语学习app分析

    以下数据分析由队员张波收集整理队员链接 队友的博客 一.数据统计 为了让统计数据更加准确可信,我们选取了三款android平台的应用市场软件作为数据的来源. 英语学习app下载量统计表: 序号 应用名 ...

  5. jquery 城市三级联动

    js代码 /*城市三级联动 * @method cityChange * @param allProvince,allCity,allDistrict */ function cityChange(p ...

  6. 用world写blog

    一级目录 怎么写呢? 这个和markdown那个更加方便呢? 据说插入表格有问题 我试一试         二级目录 这个大小还不错 添加第三季目录呢 三级目录 添加目录必须要用鼠标么? #inclu ...

  7. spring mvc <mvc:default-servlet-handler /> 。

    spring mvc配置 <mvc:default-servlet-handler /> 时. 提示 The prefix "mvc" for element &quo ...

  8. (分享)多功能 PDF转换器v3.0版本

    转换的效果非常不错,值得使用.破解成功的截图:这个程序必须随便输入注册码注册,不然会有水印的. 这是程序主界面了 正在测试pdf转word过程,转换结果个人感觉非常不错,跟原版pdf的格式非常接近,个 ...

  9. Ajax请求数据

    后台使用数数组的形式存放数据(以键值对的形式存放).让后再Json转码. Map<String,String> map=new HashMap<String,String>() ...

  10. centos6.5 用户管理

    linux 用户管理 命令:useradd 选项: -c comment 备注信息 -d 用户目录 usr/test 不存在 则 -m test 创建 -s shell文件,指定用户的登录Shell. ...