【iOS】关于kvc中的setValuesForKeysWithDictionary为model赋值的一些常见知识
来源:互联网 发布:淘宝金鹰男士 假货 编辑:程序博客网 时间:2024/06/01 08:21
在我们些项目的时候,很多时候我们会用到model,并且挺方便。当然成熟的第三方也很多,比如:jsonmodel 和MJ的model。。。
有时候我们也可以简单的的实现,那就是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都得到相应的转换。
2 0
- 【iOS】关于kvc中的setValuesForKeysWithDictionary为model赋值的一些常见知识
- 5、关于kvc中的setValuesForKeysWithDictionary为model赋值
- iOS KVC setValuesForKeysWithDictionary的使用
- 字典的快速赋值model: setValuesForKeysWithDictionary
- iOS 字典的快速赋值 setValuesForKeysWithDictionary
- iOS 获取可采用KVC为对象赋值的keys
- iOS学习之KVC中setValuesForKeysWithDictionary:
- iOS 开发之 KVC - setValuesForKeysWithDictionary 解析神器
- 字典的快速赋值 setValuesForKeysWithDictionary
- 字典的快速赋值 setValuesForKeysWithDictionary
- 字典的快速赋值 setValuesForKeysWithDictionary
- KVC中setValuesForKeysWithDictionary:(写的不错)
- 关于IOS的一些知识
- iOS --- 关于KVC使用的一些小技巧
- 关于SEO的一些常见知识
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- KVC中setValuesForKeysWithDictionary:
- 在mac状态栏上显示应用程序图标,代码
- Android官方文档阅读之旅——Animation and Graphics Overview 动画与图形概述
- final,finally和finalize的使用
- CentOS安装Code::Blocks
- UML学习---2
- 【iOS】关于kvc中的setValuesForKeysWithDictionary为model赋值的一些常见知识
- 两个viewport的故事(第二部分)
- 多线程 死锁
- QSettings 与中文(反斜杠 转义)
- GCD实现倒计时
- java上转型
- mysql 对取当前日期周一和周日语句的详细解析
- 栈与递归
- 解压静态库.a文件