iOS.OC.03 KVO-索引值觀察者,ios.oc.03kvo-
KVO Key,Value,Observing,即索引值觀察者。它提供了這樣一種機制,當指定對象的屬性發生改變時,KVO會自動通知相應的觀察者。
它與NSNotification不同,鍵-值觀察中並沒有所謂的中心對象來為所有觀察者 提供變化通知。取而代之地,當有變化發生時,通知被直接發送至處於觀察狀態的對象。
三個步驟:註冊觀察者,接收變更通知,移除觀察者。執行個體如下:
建立一個工程,建立兩個類,一個Baby,一個Mother。Baby有一個屬性hungryNum,叫饑餓值吧,當饑餓值改變的時候mother接收饑餓值變更。
Baby.h
#import <Foundation/Foundation.h>
@interface Baby : NSObject
@property(nonatomic,assign)NSInteger hungryNum;
@end
Mother.m
#import "Mother.h"
@implementation Mother
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if ([keyPath isEqualToString:@"hungryNum"]) {
//每當監聽的屬性hungryNum改變時,列印hungryNum的當前值和之前值。
NSLog(@"%@ %@",[change objectForKey:@"new"],[change objectForKey:@"old"]);
}
}
@end
ViewController.m
#import "ViewController.h"
#import "Baby.h"//引入標頭檔
#import "Mother.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Baby * xiaoxiao=[[Baby alloc]init];//建立對象
Mother * xiaoMama=[[Mother alloc]init];
//註冊觀察者,xiaoxiao添加了觀察者xiaoxiaoMama,觀察hungryNum屬性。
[xiaoxiao addObserver:xiaoMama forKeyPath:@"hungryNum" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
xiaoxiao.hungryNum=10;//給xiaoxiao的hungryNum屬性附一個初值,用一個for迴圈使得該屬性的值改變,每次值改變都會通知監聽者。
for (xiaoxiao.hungryNum; xiaoxiao.hungryNum>0; xiaoxiao.hungryNum--) {
}
//移除觀察者,注意:如果不移除,程式運行到此會奔潰。
[xiaoxiao removeObserver:xiaoMama forKeyPath:@"hungryNum"];
}
列印結果:
2015-03-21 17:11:29.735 OMG[2366:148640] 10 0
2015-03-21 17:11:29.736 OMG[2366:148640] 9 10
2015-03-21 17:11:29.736 OMG[2366:148640] 8 9
2015-03-21 17:11:29.736 OMG[2366:148640] 7 8
2015-03-21 17:11:29.736 OMG[2366:148640] 6 7
2015-03-21 17:11:29.736 OMG[2366:148640] 5 6
2015-03-21 17:11:29.736 OMG[2366:148640] 4 5
2015-03-21 17:11:29.737 OMG[2366:148640] 3 4
2015-03-21 17:11:29.737 OMG[2366:148640] 2 3
2015-03-21 17:11:29.737 OMG[2366:148640] 1 2
2015-03-21 17:11:29.737 OMG[2366:148640] 0 1
如有錯誤,請不吝賜教,必改之。