字典的快速赋值 setValuesForKeysWithDictionary

前言

在学习解析数据的时候,我们经常是这么写的:
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. 【iOS开发】字典的快速赋值 setValuesForKeysWithDictionary

    前言 在学习解析数据的时候,我们经常是这么写的:PersonModel.h文件中 @property (nonatomic,copy)NSString *name; @property (nonato ...

  2. jQuery对json快速赋值

    jQuery对json快速赋值,重点在于将input的id取跟JSON同样的名称. <!DOCTYPE html> <html> <head lang="en& ...

  3. 用字典给Model赋值并支持map键值替换

    用字典给Model赋值并支持map键值替换 这个是昨天教程的升级版本,支持键值的map替换. 源码如下: NSObject+Properties.h 与 NSObject+Properties.m / ...

  4. 用字典给Model赋值

    用字典给Model赋值 此篇教程讲述通过runtime扩展NSObject,可以直接用字典给Model赋值,这是相当有用的技术呢. 源码: NSObject+Properties.h 与 NSObje ...

  5. iOS开发之--字典快速赋值

    以往在学习解析数据的时候,我们用的方法都是一个一个生命,然后加到字典里面,然后进行复制,那样的麻烦,而且也不能保证一次成功,不出错,我是遇到过多次key值的问题! 其实可以把复制的过程替换成一句话: ...

  6. 总结day5 ---- ,字典的学习,增删改查,以及字典的嵌套, 赋值运算

    内容大纲: 一:字典的定义 二:字典的增加 >1:按照key增加,  无则增加,有则覆盖 >2:setdefault()  ,无则增加,有则不变 三:字典的删除 >1:pop()  ...

  7. TDictionary字典 记录 的赋值。

    type TRen = record age: Integer; //把name定义成结构的属性. private Fname: string; procedure Setname(const Val ...

  8. .NET通过字典给类赋值

    /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam& ...

  9. [python]字典的直接赋值、浅拷贝和深拷贝解析

    1.赋值引用 b = a: a 和 b 都指向同一个对象. 2.浅拷贝 b = a.copy():  a 和 b父对象是一个独立的对象,但他们的子对象还是指向统一对象(是引用). 3.深拷贝 b = ...

随机推荐

  1. hdu 1404 找sg ***

    HDU 1404  Digital Deletions 一串由0~9组成的数字,可以进行两个操作:1.把其中一个数变为比它小的数:2.把其中一个数字0及其右边的所以数字删除. 两人轮流进行操作,最后把 ...

  2. 深入理解ASP.NET 5的依赖注入

    (此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:ASP.NET 5整个底层都架构于依赖注入机制之下,今天介绍的文章详细介绍了内置依赖注 ...

  3. 监听报错 TNS-00525: Insufficient privilege for operation 11gR2 + 连接报错ORA-12537: TNS:connection closed

    1.TNS-00525: Insufficient privilege for operation Started with pid= Listening on: (DESCRIPTION=(ADDR ...

  4. Tips for OpenMesh

    OpenMesh 求两点之间的距离 MyMesh::Point p1(1,2,3); MyMesh::Point p2(1,2,5); double d=(p1-p2).length();

  5. maven web启动报错java.lang.ClassNotFoundException: org.springframework.web.util.Log4jConfigListener

    问题描述 SEVERE: Error configuring application listener of class org.springframework.web.util.Log4jConfi ...

  6. FZU Problem 2082 过路费 树链剖分

    Problem 2082 过路费    Problem Description 有n座城市,由n-1条路相连通,使得任意两座城市之间可达.每条路有过路费,要交过路费才能通过.每条路的过路费经常会更新, ...

  7. C语言基本点初探

    1,对于int a=10++;此语句错误,为什么呢,对于i++来说,i是一个变量,是把i加1然后赋值给i,然而10不是一个变量所以无法执行加加的语法; 2,运算符的优先级: 赋值运算符<逻辑运算 ...

  8. PrograssBar的setIndeterminateDrawable不起作用

    是设置绘制不显示进度的进度条的Drawable对象 使用中发现,在xml中设置IndeterminateDrawable可以正常使用,但是如果需要在代码中更换图片使用setIndeterminateD ...

  9. SQL2000/2005字符串拆分为列表通用函数

    ------------------------------------------------------------------ --  Author : htl258(Tony) --  Dat ...

  10. Git的安装与使用

    1,下载git https://code.google.com/p/msysgit/downloads/list 2,安装git ,我们选择命令行形式,这样无论在window下还是在linux下 都可 ...