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.
相关文章
相关标签/搜索