本节简单探究KVC、KVO的使用,下节探究组成原理。
一、Key-Value Coding(KVC)即是指 NSKeyValueCoding,一个非正式的 Protocol,提供一种机制来间接访问对象的属性。KVO 就是基于 KVC 实现的关键技术之一。
支持这种访问的主要方法是:
(id)valueForKey:(NSString *)key;
- (void)setValue:(id)value forKey:(NSString *)key;
- (id)valueForKeyPath:(NSString *)keyPath;
- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;
例:
1、PersonObject有一个name属性,那么就有一个value对应他的name这个key。
<span style="font-size:14px;"> PersonObject * personInstance = [[PersonObject alloc]init];
[personInstance setValue:@"老师" forKey:@"name"];
NSLog(@"%@",[personInstance valueForKey:@"name"]);</span>
2、PersonObject的有一个key (one)。one的有一个name的key。
<span style="font-size:14px;"> OtherPersonObject *one = [[OtherPersonObject alloc]init];
personInstance.otherPerson = one;
[personInstance setValue:@"学生" forKeyPath:@"otherPerson.otherPersonName"];
NSLog(@"%@",[personInstance valueForKeyPath:@“otherPerson.otherPersonName”]);</span>
以上是kvc的基本知识。
二、Key-Value Observing (KVO) 建立在 KVC 之上,它能够观察一个对象的 KVC key path 值的变化。
•addObserver: forKeyPath: options: context:添加观察者。
•observeValueForKeyPath:ofObject:change:context: 在被观察的 key path 的值变化时调用。
•dealloc 停止观察,做对应的移除操作。
例:我们用personInstance来监听一个BankObject对象的accountBalance的变化。
<span style="font-size:14px;">BankObject *bankInstance = [[BankObject alloc]init];
[bankInstance addObserver:personInstance forKeyPath:@"accountBalance" options:NSKeyValueObservingOptionNew context:@“参数信息"];</span>
<span style="font-size:14px;">#import "PersonObject.h"
@implementation PersonObject
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"改变了");
NSLog(@"%@",context);
}
@end
</span>
改变accountBalance的值
<span style="font-size:14px;">bankInstance.accountBalance = 2;</span>
打印信息:
2014-11-17 17:03:14.525 RuntimeTest[1613:787198] 老师
2014-11-17 17:03:14.526 RuntimeTest[1613:787198] 学生
2014-11-17 17:03:14.526 RuntimeTest[1613:787198] 改变了
2014-11-17 17:03:14.526 RuntimeTest[1613:787198] 参数信息
最后移除监听:
<span style="font-size:14px;">[bankInstance removeObserver:personInstance forKeyPath:@"accountBalance"];</span>
这就是 KVO 的作用,它通过 key path 观察对象的值,当值发生变化的时候会收到通知。
以上是基本的KVO, 第二节会深层次探究KVC、KVO。