views:

517

answers:

2

I have a fairly complex iphone application that has many asynchronous processes occurring. To deal with this I'm making heavy use of NSNotification Center. My question is what is the "best practice", if such a thing exists", for registering the notifications? Right now they sprinkled through my code in a hap-hazard way. I'm about to go to production and I want it cleaned up. I though about having a "registerNotifications" method in viewDidLoad of the main view which obviously registers all notifications in one shot. Does this sound reasonable? If not what would be the preferred way of dealing with this. Thanks in advance for your help!!

A: 

An object should register itself as an observer of the notifications it is interested in. The best time to do it is when the object becomes interested, otherwise you have to deal with notifications when you don't want them.

Graham Lee
so in other words your saying I should leave them sprinkled throughout the code?
ennuikiller
+3  A: 

Putting all the notifications in one object destroys encapsulation and that is bad. You make one objects notification operations dependent on another object working properly. It will actually be a nightmare tracking all that. It is also backwards to the entire of purpose of notifications which is to create a decentralized and modular messaging system.

Notifications shouldn't be "sprinkled throughout the code" but they should be managed solely by the objects that receive them. If you use a great deal of notifications you might need to create a class with dedicated methods for handling multiple notifications and then have your other classes inherit from that class. That way you get automatic management.

One of the big mistakes people make with notifications is that they register controllers when they really need to register their data model. For example, suppose you're downloading some data from a URL and you want to update the interface as it progresses and/or when it ends. If you have multiple views in your UI and you register controllers, then every view has to manage a notification (of which there may be more than one.) However, if you set up the shared datamodel to receive the notification you need only have a maximum of two notifications. One will go to the datamodel so the datamodel can update itself and then you can have the datamodel issue a generic notification for any listening views to update themselves from the datamodel.

Making your view controller dependent on the datamodel simplifies design greatly in all cases.

TechZen
excellent answer thanks!
ennuikiller