本節簡單探究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。