【iOS】关于kvc中的setValuesForKeysWithDictionary为model赋值的一些常见知识
2015-11-25 12:28
615 查看
在我们些项目的时候,很多时候我们会用到model,并且挺方便。当然成熟的第三方也很多,比如:jsonmodel 和MJ的model。。。
有时候我们也可以简单的的实现,那就是kvc中的setValuesForKeysWithDictionary
这样我们的一个people的model就已经创建完了
这样我们就可以吧字典的里面的东西给model对象了,是不是很简单呢。
2、如果服务返回的字符串有系统默认不能使用的属性(例如:id ,description等可以进行转换)
代码如下:
有时候我们也可以简单的的实现,那就是kvc中的setValuesForKeysWithDictionary
1、我们要创建一个model
// // People.h // KVCTest // // Created by Mac on 15/11/25. // Copyright (c) 2015年 wmeng. All rights reserved. // #import <Foundation/Foundation.h> @interface People : NSObject @property (nonatomic,strong) NSString *name; @property (nonatomic,strong) NSString *age; @property (nonatomic,strong) NSString *height; @property (nonatomic,strong) NSString *weight; @property (nonatomic,strong) NSString *sex; @end
这样我们的一个people的model就已经创建完了
2、使用setValuesForKeysWithDictionary
执行代码:// 1、创建一个字典 NSDictionary *dic = @{@"name":@"zhanshang",@"age":@"20",@"height":@"120",@"weight":@"120",@"sex":@"男"}; // 2、创建对象接受 People *p = [[People alloc]init]; [p setValuesForKeysWithDictionary:dic]; NSLog(@"%@\n%@\n%@\n%@\n%@\n%@",p,p.name,p.age,p.weight,p.height,p.sex);3、运行结果:
这样我们就可以吧字典的里面的东西给model对象了,是不是很简单呢。
但是中间也会遇到一下常见的问题,那就是,字典里面有多余的keyValue,但是people没有定义,使用setValuesForKeysWithDictionary就会崩溃了,
解决办法:(在people.m文件加入一个方法就可以解决-(void)setValue:(id)value forUndefinedKey:(NSString *)key)
// // People.m // KVCTest // // Created by Mac on 15/11/25. // Copyright (c) 2015年 wmeng. All rights reserved. // #import "People.h" @implementation People //对未定义key的处理方法 -(void)setValue:(id)value forUndefinedKey:(NSString *)key { } @end
最后介绍一下-(void)setValue:(id)value forUndefinedKey:(NSString *)key的方法的一些用处:
1、当实现这个方法以后,对未定义的keyValue的处理。2、如果服务返回的字符串有系统默认不能使用的属性(例如:id ,description等可以进行转换)
代码如下:
//对未定义key的处理方法 -(void)setValue:(id)value forUndefinedKey:(NSString *)key { if ([key isEqualToString:@"id"]) { self.id1 = value; } if ([key isEqualToString:@"description"]) { self.description1 = value; } }这样,id和description都得到相应的转换。
相关文章推荐
- UITableViewCell中的使用cell和cell.contentView的区别
- 225. Implement Stack using Queues
- git#gui
- Codeforces Round #333 (Div. 1) B. Lipshitz Sequence 倍增 二分
- 1188 - Fast Queries (莫队算法)
- [LeetCode255]Verify Preorder Sequence in Binary Search Tree
- 使用document.getElementsByName("name")获取元素的value值
- AudioConverterNew from AudioQueueNew returned 'fmt?'
- 被预加载的页面无法在mui.init中去成功预加载其他页面的问题
- 1100 - Again Array Queries (鸽笼定理)
- servlet request getHeader(“x-forwarded-for”) 获取真实IP
- UITextView的字数限制 及 添加自定义PlaceHolder
- 为什么要使用ToStringBuilder
- 10分钟精通require.js
- UESTC 1218 Pick The Sticks (dp )
- UIView 翻转动画
- bluetooth handfree client test on console
- UIButton 点击后变灰
- TinyOS论文03:Bugs or Anomalies? Sequence Mining based Debugging in Wireless Sensor Networks
- Fluent API 配置