ios学习8_KVC和字典转模型
Key Value Coding是cocoa的一个标准组成部分,它能让我们能够通过name(key)的方式訪问属性,某些情况下极大地简化了代码。可称之为cocoa的大招。
例如以下的样例:
使用KVC的优点
不使用KVC
- (id)tableView:(NSTableView *)tableview
objectValueForTableColumn:(id)column row:(NSInteger)row {
ChildObject *child = [childrenArray objectAtIndex:row];
if ([[column identifier] isEqualToString:@"name"]) {
return [child name];
}
if ([[column identifier] isEqualToString:@"age"]) {
return [child age];
}
if ([[column identifier] isEqualToString:@"favoriteColor"]) {
return [child favoriteColor];
}
// And so on.
}
使用KVC
- (id)tableView:(NSTableView *)tableview
objectValueForTableColumn:(id)column row:(NSInteger)row {
ChildObject *child = [childrenArray objectAtIndex:row];
return [child valueForKey:[column identifier]];
}
显而易见,简化了非常多代码。
KVC操作
KVC赋值
1 给当前对象属性赋值
- (void)setValue:(id)value forKey:(NSString *)key;
2给对象的属性的属性赋值
- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
3 处理没有定义的键
- (void) setValue:(id)value forUndefinedKey:(NSString *)key
4 字典转模型:会为我们把和dictionary的key名字同样的class proerty设置上dict中key相应的value
- (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues;
注意:要求字典中的key和对象属性一样。都是主要的OC数据类型:Array/Dictionary/Boolean/Data/Number/String
KVC取值
1 获取对象属性的值
- (id)valueForKey:(NSString *)key;
2 获取对象属性的属性的值
- (id)valueForKeyPath:(NSString *)keyPath;
样例:
Person * p = [[Person alloc]init];
Car *car = [[Car alloc]init];
p.car = car;
[p setValue:@"qhyuan" forKeyPath:@"name"];
[p setValue:@(20) forKey:@"id"];
[p setValue:@"baoshijie" forKeyPath:@"car.brand"];
[p setValue:@"180000" forKeyPath:@"car.price"];
NSLog(@"kvc賦值的person对象----%@",p);
NSString * name = [p valueForKey:@"name"];
NSString * brand = [p valueForKeyPath:@"car.brand"];
NSLog(@"%@ %@",name, brand);
字典转模型
常规情况
模型
Person.h
@interface Person : NSObject
@property (nonatomic, copy) NSString * name;
@property (nonatomic, assign) int age;
- (instancetype) initWithDict:(NSDictionary *) dict;
+ (instancetype) personWithDict:(NSDictionary *) dict;
+ (NSArray *) person;
@end
Person.m
@implementation Person
- (instancetype) initWithDict:(NSDictionary *) dict
{
if(self = [self init])
{
// 使用KVC 字典转模型 如此方便。省去了大量的赋值代码
[self setValuesForKeysWithDictionary:dict];
//self.name = dict[@"name"];
//self.age = [dict[@"age"] integerValue];
}
return self;
}
+ (instancetype) personWithDict:(NSDictionary *) dict
{
return [[self alloc]initWithDict:dict];
}
+ (NSArray *) person
{
NSMutableArray * mutablePersons = [NSMutableArray array];
NSString * path = [[NSBundle mainBundle] pathForResource:@"persons.plist" ofType:nil];
NSArray *persons = [[NSArray alloc] initWithContentsOfFile:path];
for (NSDictionary * person in persons) {
[mutablePersons addObject:[self personWithDict:person]];
}
return mutablePersons;
}
- (NSString *) description
{
NSString * desc = [NSString stringWithFormat:@"<%p:(%@,%d)>",self,self.name,self.age];
return desc;
}
@end
字典中多个某些key是OC中的keyword
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
假设将键age换成了id
会抛出异常:
*** Terminating app due to uncaught exception 'NSUnknownKeyException',reason: '[<Person 0x8c419a0> setValue:forUndefinedKey:]: this class isnot key value coding-compliant for the key id.
重写下面方法就可以,处理没有定义的键
- (void)setValue:(id)value forUndefinedKey:(NSString *)key;
解决方案:
- (void) setValue:(id)value forUndefinedKey:(NSString *)key
{
if([key isEqualToString:@"id"])
key = @"age";
[super setValue:value forKey:key];
}
字典里面还包括某些相应自己定义类的字典或者数组
Person类添加了一个Car类型的属性
@property (nonatomic, strong) Car * car;
我们仅仅须要重写下面方法
- (void)setValue:(id)value forKey:(NSString *)key;
解决方法:
- (void)setValue:(id)value forKey:(NSString *)key
{
if([key isEqualToString:@"cars"])
{
Car *car = [Car carWithDict:(NSDictionary *)value];
self.car = car;
}
else
[super setValue:value forKey:key];
}
打印结果
字典转模型[5525:60b] (
"<Person:(zhangsan,20,<Car:(benchi,180000)>)>",
"<Person:(lisi,22,<Car:(baoma,180000)>)>",
"<Person:(wangwu,24,<Car:(aodi,180000)>)>"
)
假设不仅仅是添加了Cars属性而是添加了Cars数组,也是类似的方式。
ios学习8_KVC和字典转模型的更多相关文章
- iOS开发UI篇—字典转模型
iOS开发UI篇—字典转模型 一.能完成功能的“问题代码” 1.从plist中加载的数据 2.实现的代码 // // LFViewController.m // 03-应用管理 // // Creat ...
- iOS 懒加载 字典转模型
>>>懒加载 一.介绍 懒加载又称延时加载,即在系统调用时加载,如果系统不调用则不会加载,所谓懒加载其实就是重写其get方法. 在使用懒加载时要先判断该方法是否存在,如果不存在再进行 ...
- 字典转模型框架 Mantle的使用:国外程序员最常用的iOS模型
Mantle简介 Mantle 是iOS和Mac平台下基于Objective-C编写的一个简单高效的模型层框架. Mantle能做什么 Mantle可以轻松把JSON数据.字典(Dictionary) ...
- iOS开发—字典转模型,KVC设计模式
iOS开发UI基础—字典转模型 开发中,通常使用第三方框架可以很快的实现通过字典转模型,通过plist创建模型,将字典的键值对转成模型属性,将模型转成字典,通过模型数组来创建一个字典数组,通过字典数组 ...
- iOS学习笔记38-MJExtension使用
一.MJExtension第三方框架 我们在iOS开发过程中,我们常常需要将字典数据(也就是JSON数据)与Model模型之间的转化,例如网络请求返回的微博数据.等等,如果我们自己全部手动去创建模型并 ...
- ios开发runtime学习五:KVC以及KVO,利用runtime实现字典转模型
一:KVC和KVO的学习 #import "StatusItem.h" /* 1:总结:KVC赋值:1:setValuesForKeysWithDictionary实现原理:遍历字 ...
- ios开发网络学习二:URL转码以及字典转模型框架MJExtension的使用
一:url转码,当url中涉及到中文的时候,要考虑转码,用UTF8对中文的url进行转码 #import "ViewController.h" @interface ViewCon ...
- iOS开发——高级技术精选OC篇&Runtime之字典转模型实战
Runtime之字典转模型实战 如果您还不知道什么是runtime,那么请先看看这几篇文章: http://www.cnblogs.com/iCocos/p/4734687.html http://w ...
- iOS开发——网络篇——JSON和XML,NSJSONSerialization ,NSXMLParser(XML解析器),NSXMLParserDelegate,MJExtension (字典转模型),GDataXML(三方框架解析XML)
一.JSON 1.JSON简介什么是JSONJSON是一种轻量级的数据格式,一般用于数据交互服务器返回给客户端的数据,一般都是JSON格式或者XML格式(文件下载除外) JSON的格式很像OC中的字典 ...
随机推荐
- 网页显示403. That’s an error的解决方法。
使用Go*gent打开网页,经常出现403. That’s an error.下面是解决的方法. 方法/步骤 一.打开Go*gent的文件目录.不知道找文件目录的,可以在桌面上右键点击Go*g ...
- thinkphp5生成二维码
1.运用composer下载拓展到vendor下 composer require aferrandini/phpqrcode 2.common.php 里面写生成二维码函数 <?php // ...
- Oracle中如何插入特殊字符: &amp; 和 &#39; (多种解决方案)
Oracle中如何插入特殊字符:& 和 ' (多种解决方案)今天在导入一批数据到Oracle时,碰到了一个问题:Toad提示要给一个自定义变量AMP赋值,一开始我很纳闷,数据是一系列的Inse ...
- Oracle排名函数(Rank)实例详解
这篇文章主要介绍了Oracle排名函数(Rank)实例详解,需要的朋友可以参考下 --已知:两种排名方式(分区和不分区):使用和不使用partition --两种计算方式(连续,不连续),对应 ...
- mxnet.base.MXNetError: src/imperative/./imperative_utils.h:70: Check failed: inputs[i]->ctx().dev_mask() == ctx.dev_mask() (1 vs. 2)
mxnet 训练错误: mxnet.base.MXNetError: [14:42:22] src/imperative/./imperative_utils.h:70: Check failed: ...
- Educational Codeforces Round 58 (Rated for Div. 2) (前两题题解)
感慨 这次比较昏迷最近算法有点飘,都在玩pygame...做出第一题让人hack了,第二题还昏迷想错了 A Minimum Integer(数学) 水题,上来就能做出来但是让人hack成了tle,所以 ...
- luogu 4884 多少个1?
题目描述: 给定整数K和质数m,求最小的正整数N,使得 11111⋯1(N个1)≡K(mod m) 说人话:就是 111...1111 mod m =K 题解: 将两边一起*9+1,左边就是10^an ...
- IO之Print流举例
import java.io.*; public class TestPrintStream1 { public static void main(String[] args) { PrintStre ...
- String类的概述和构造方法
StringDemo.java /* * String:字符串类 * 由多个字符组成的一串数据 * 字符串其本质就是一个字符数组 * * 构造方法: * String(String original) ...
- 《 阿Q正传》-鲁迅 词语解释 | 经典语录
词语解释 “太上有立德,其次是立功,其次是立言,虽久不废,此之谓不朽”.-出自<左传>-左丘明(春秋末期) 解释:(1)最上等的是树立德行,其次是建功立业,再其次是创立学说,即使过了很久也 ...