iOS KVO(Key-Value Observing)總結

KVO 容許觀察者對被觀察對象的特定屬性的值進行觀察,若是被觀察對象的特定值更改,會觸發一個observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context的方法。 性能

KVO與NSNotificationCenter有不少類似的地方。首先,KVO須要給被觀察者添加觀察者,addObserver:forKeyPath:options:context:.取消觀察,用removeObserver:forKeyPath:context:. code

KVO與NSNotificationCenter不一樣的是,你不用去手動調用某個方法,若是沒有觀察者到狀況下,廣播是會發送到,而KVO則不會執行。KVO只會在有觀察者對象到狀況下才會執行通知方法。這使得KVO在某些對性能要求很高的地方,是一個很好到選擇。 server

註冊觀察者 對象

- (void)registerAsObserver
{
  [object addObserver:inspector
          forKeyPath:@"someProperty"
            options:NSKeyValueObservingOptionNew
            comtext:NULL];
}
接受通知

- (void)observeValueForKeyPath:(NSString *)keyPath
                       ofObject:(id)object
                          change:(NSDictionary *)change
                          context:(void *)context
{
        if(someCondition)
        {
           //do something
        }

        /*
          Be sure to call the superclass's implementation
          * if it implements it *
          NSObject does not implement the method.
         */
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                              change:change
                               context:context];
}
取消觀察者

- (void)unregisterForChangeNotification
{
   [observedObject removeObserver:inspector forKeyPath:@"someProperty"];
}

關於如何查看一個對象是否有觀察者, rem

在網上查了一下,有一個[object observationInfo]的方法,若是沒有觀察者返回nil. it

對對象刪除觀察者還能夠用 io

@try
{
  [object removeObserver:inspector forKeyPath:@"someProperty"];
}
@catch (NSException *e)
{
}
來防止對一個沒有觀察者的對象刪除形成程序crash.
相關文章
相關標籤/搜索