Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between NSNotificationCenter and the Key Value Observing technique?

I just read a couple of tutorials regarding KVO, but I have not yet discovered the reason of its existence. Isn't NSNotificationCenter an easier way to observe objects?

I am new to Stackoverflow, so just tell me if there is something wrong in the way I am asking this question!

like image 307
Erik Avatar asked Aug 12 '11 13:08

Erik


1 Answers

Notifications and KVO serve similar functions, but with different trade-offs.

  • Notifications are easy to understand. KVO is... challenging... to understand (at least to understand how to use it well).

  • Notifications require modification to the observed code. The observed must explicitly generate every notification it offers. KVO is transparent to the observed code as long as the observed code conforms to KVC (which it should anyway).

  • Notifications have overhead even if you don't use them. Every time the observed code posts a notification, it must be checked against every observation in the system, even if no one is observing that object (even if no one is observing anything). This can be very non-trivial if there are more than a few hundred observations in the system. It can be a serious problem if there are a few thousand. KVO has zero overhead for any object that is not actually observed.

In general, I discourage KVO because of some specific implementation problems that I believe make it hard to use correctly. It's difficult to observe an object that your superclass also observes without special knowledge of your superclass. Its heavy reliance of string literals make small typos hard to catch at compile time. In general, I find code that relies heavily on it becomes complex and hard to read, and begins to pick up spooky-action-at-a-distance bugs. NSNotification code tends to be more straightforward and you can see what's happening. Random code doesn't just run when you didn't expect it.

All that said, KVO is an important feature and developers need to understand it. More and more low-level objects rely on it because of it's zero-overhead advantages. But for new developers, I typically recommend that they rely more on notification rather than KVO.

There is a third way. You can keep a list of listeners, and send them messages when things change, just like delegate methods. Some people call these "multicast delegates" but "listeners" is more correct here because they don't modify the object's behavior as a delegate does. Doing it this way can be dramatically faster than NSNotification if you need a lot of observation in a system, without adding the complexity of KVO.

like image 167
Rob Napier Avatar answered Nov 18 '22 02:11

Rob Napier