Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pros and Cons of Listener/Observer approaches to notify Model changes

In any typical iPhone application, there will be model classes that are responsible for data loading/parsing. Upon completion of the data loading/parsing tasks, the affected controllers needed to be notified of the change in the model and update the view accordingly.

There are several listener/observer approaches for this in iPhone application development. What are the pros/cons and reasons for using each of the following approaches?

  1. KVO
  2. NSNotification
  3. Delegate
  4. Any other known approach
like image 563
Ronnie Liew Avatar asked Jan 03 '10 15:01

Ronnie Liew


1 Answers

In my own experience:

Delegation:

  • PRO: use only when you have a single object to notify;
  • PRO: using an explicit protocol you can document clearly your intentions;
  • CON: can be the source of crashes and memory leaks if wrongly used (tip: don't retain delegates, assign them, and remember to deassign delegates when / if they are released!)

I wrote about memory management problems generated by delegation in this article on my blog:

http://akosma.com/2009/01/28/10-iphone-memory-management-tips/

NSNotification:

  • PRO: better when you have several objects to notify;
  • PRO: very flexible, leads to loosely-coupled classes;
  • CON: notifications are sent synchronously (so make sure your individual notification handlers only do very little)
  • CON: sometimes hard to document and maintain. Be sure to clearly explain in header docs what each notification means and when it is sent.

KVO:

  • Similar concerns about NSNotifications;
  • CON: even more obscure to document. Be sure to add more header docs or architectural tips on your comments to explain who's listening what. I personally wouldn't use KVO for data loading or parsing tasks.

Personally, when dealing with network-enabled apps talking to a remote web service, I use a singleton data loader class (wrapping ASIHTTPRequest and handling all the serialization and deserialization) which pops notifications when something occurs. This way I can have the app delegate handling connection errors on its own (popping up alerts and such if required), and each controller only cares about the responses it wants.

Of course, this approach depends on the application, but this general architecture might be a starting point for your own code.

like image 161
Adrian Kosmaczewski Avatar answered Oct 04 '22 21:10

Adrian Kosmaczewski