11

我想知道是否有理由在 KVO vs NSNotificationCenter 观察中使用一个。性能、内存使用、速度等?

4

2 回答 2

15

两者并不总是可以互换的。从概念上讲,KVO 仅用于观察对象的属性。例如,您不能使用 KVO 替换NSApplicationWillTerminateNotification,因为它通知观察者事件发生,而不是对象属性的更改。

至于性能和内存使用,它们都很快并且使用的内存可以忽略不计。NSNotificationQueue已合并以阻止大量通知。据我所知,KVO 没有任何合并,这确实在某一时刻给我带来了性能问题。我观察了数百个对象,当这些对象发生批量更新时,我会收到数百个 KVO 回调。这不是 KVO 本身的性能问题,而是由于批量更新而运行的我自己的代码。

性能并不是真正的问题,更多的是最适合该问题。如果是属性更改,请使用 KVO。如果不是属性更改,请使用委托或通知,具体取决于您需要单个观察者还是多个观察者。

于 2011-09-20T04:04:41.683 回答
1

A very old question, but thought of adding some points. I agree with Tom Dalling's answer, however, there are many scenarios in big applications where we tend to add observer for a property of an object and we cannot, or, we miss out removing them from list of observers.

Let us consider the following scenario from my application - A ViewController displays a snake object, I am observing for a property change on this object - "venom". So whenever viewController needed to show a different snake I would simply remove the view controller from observer of that snake object.

The app evolved to show a list of snakes instead of a single snake, this means I had to observe for property of all snakes in that object. Now, when an old snake is removed from the array I should get to know about this event so that I can remove view controller as observer from this snake object. To do this, I have to first observe for changes on the array itself. To do this I have to follow particular protocol to insert objects into array and remove them from array. This way the complexity builds on. We all do know the consequences of not removing observer from an object and if that object is released by the OS!

Above is just one example to cite, the main problem here is I cannot get the list of KVO observers for a given object to remove them from observers before this object gets released - This can be easily achieved by NSNotification and NSNotificationCenter. At times, I tend to be inclined towards using NSNotification over KVO, however, KVO always has edge over notification in terms of good design practice.

于 2015-02-17T06:29:47.243 回答