kvo,kvc
来源:互联网 发布:大屏数据 编辑:程序博客网 时间:2024/06/14 08:57
KVO,即:Key-Value Observing 建立在 KVC 之上,它能够观察一个对象的 KVC key path 值的变化,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知。简单的说就是每次指定的被观察的对象的属性被修改后,KVO就会自动通知相应的观察者了。
KVC,即是指 NSKeyValueCoding,一个非正式的 Protocol,提供一种机制来间接访问对象的属性
一个对象拥有某些属性。比如说,一个 Person 对象有一个 name 和一个 address 属性。以 KVC 说法,Person 对象分别有一个 value 对应他的 name 和 address 的 key。 key 只是一个字符串,它对应的值可以是任意类型的对象。从最基础的层次上看,KVC 有两个方法:一个是设置 key 的值,另一个是获取 key 的值。如下面的例子:
1
2
3
4
5
6
7
8
9
10
11
12
void
changeName(Person *p, NSString *newName)
{
// using the KVC accessor (getter) method
NSString *originalName = [p valueForKey:@
"name"
];
// using the KVC accessor (setter) method.
[p setValue:newName forKey:@
"name"
];
NSLog(@
"Changed %@'s name to: %@"
, originalName, newName);
}
现在,如果 Person 有另外一个 key 配偶(spouse),spouse 的 key 值是另一个 Person 对象,用 KVC 可以这样写:
1
2
3
4
5
6
7
8
9
10
11
12
13
void
logMarriage(Person *p)
{
// just using the accessor again, same as example above
NSString *personsName = [p valueForKey:@
"name"
];
// this line is different, because it is using
// a "key path" instead of a normal "key"
NSString *spousesName = [p valueForKeyPath:@
"spouse.name"
];
NSLog(@
"%@ is happily married to %@"
, personsName, spousesName);
}
key 与 key pat 要区分开来,key 可以从一个对象中获取值,而 key path 可以将多个 key 用点号 “.” 分割连接起来,比如:
[p valueForKeyPath:@
"spouse.name"
];
相当于这样……
[[p valueForKey:@
"spouse"
] valueForKey:@
"name"
];
0 0
- KVC、KVO
- KVO/KVC
- kvc 、kvo
- KVO/KVC
- KVC/KVO
- KVO/KVC
- KVC、KVO
- KVO/KVC
- KVO/KVC
- KVO/KVC
- KVC/KVO
- KVO/KVC
- KVO&KVC
- KVO & KVC
- KVC、KVO
- KVO/KVC
- kvo,kvc
- KVC、KVO
- POJ1088 滑雪
- EJS入门
- POJ Problem 1423 Big Number 【stirling公式】
- 底部Tab栏的实现(附完整代码)
- hdoj1715大菲波数(大数+打表,大数斐波那契数列)
- kvo,kvc
- C/C++笔记(C语言重要问题重讲,内存四区篇)
- 分享一个php时间段切分为指定段的函数
- 《leetcode》:Expression Add Operators
- node.js之Promise初见
- 2016微软探星夏令营:#1341 : Constraint Checker
- 简单handler实现闪屏页面跳转
- 初识Elasticsearch搜索引擎
- [HDU 5408] CRB and Farm (几何+凸包)