KVO 允许观察者对被观察对象的特定属性的值进行观察,如果被观察对象的特定值更改,会触发一个observeValueForKeyPath:(NSString )keyPath ofObject:(id)object change:(NSDictionary )change context:(void *)context的方法。
KVO与NSNotificationCenter有很多相似的地方。首先,KVO需要给被观察者添加观察者,addObserver:forKeyPath:options:context:.取消观察,用removeObserver:forKeyPath:context:.
KVO与NSNotificationCenter不同的是,你不用去手动调用某个方法,如果没有观察者到情况下,广播是会发送到,而KVO则不会执行。KVO只会在有观察者对象到情况下才会执行通知方法。这使得KVO在某些对性能要求很高的地方,是一个很好到选择。
注册观察者
- (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"];
}
关于如何查看一个对象是否有观察者,
在网上查了一下,有一个[object observationInfo]的方法,如果没有观察者返回nil.
对对象删除观察者还可以用
@try
{
[object removeObserver:inspector forKeyPath:@"someProperty"];
}
@catch (NSException *e)
{
}
来防止对一个没有观察者的对象删除造成程序crash.