2012/4/10

KVO,Key-Value Observing

KVO,Key-Value Observing
有一點類似NSNotification,但其實更像是binding

NSNotification類似Java的event流程,
但如果用NSNotification來實現binding,
就要寫setter、post、addObserver、跟對應的selector或block
若只為了監控幾個屬性的變化,就要寫好幾段程式其實挺累人的
弄不好還會提供類別間的隅和性

使用KVO可以容易的化解這個問題
example
[target addObserver:self 
    forKeyPath:@"clickCount" 
    options:NSKeyValueObservingOptionOld
    context:@selector(onEvent)];
target:欲監控的屬性的主人(sender)
addObserver:接收監控的實體(receiver)
options:(接受的值,改變前的值還是改變後的值)
context:要傳給observer的參數,這邊我們用selector,接放時則執行這個method


而observer要實作以下這個方法,來對監控事件的發生做應該處理
-(void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
{
 NSLog(@"[MyObserver]observeValueForKeyPath");
 SEL method=(SEL)context;
 [self performSelector:method];
}
相對於NSNotification,要寫的程式就少了許多

注意:
只能有@property的屬性,

沒有留言: