NSNotification: an alternative to delegation
12 Sep 2009
Sometimes, delegation is not sufficient to a task. This will occur when you need to notify multiple objects of an event. The only way to do that using delegation is to have an array of delegates, and then send the message to each one. In this case, though, NSNotification is a much better choice.
In the header file to the class that wants to post notifications (in this case, JSAutoWibbler), you must prototype the NSString identifiers of each notification type:
extern NSString * const JSAutoWibblerDidWobbleNotification;
extern NSString * const JSAutoWibblerDidWeebleNotification;
Then, in the implementation file, define those identifiers:
NSString * const JSAutoWibblerDidWobbleNotification
NSString * const JSAutoWibblerDidWeebleNotification
Now, you are prepared to post those notifications. Whenever your JSAutoWibbler wobbles, you can use message to the shared instance of NSNotificationCenter:
or, if you need to send more information along with the notification, package it in an NSDictionary and send it as the userInfo parameter:
When you have an object that you want to watch for notifications:
[[NSNotificationCenter defaultCenter] addObserver:self
The signature of any notification handlers must be in the form – (void)notificationHandlerName:(NSNotification *);; thus, didWobble: would be declared like this:
- (void)didWobble:(NSNotification *)notification;
I like to keep my notification handlers in a private category, because they should never be called outside the class in which they are implemented.
Finally, you need to remove yourself as an observer. In dealloc, do the following:
[[NSNotificationCenter defaultCenter] removeObserver:self];
Now, get coding!
Taking on another article by Jonathan Sterling on the merits of NSNotification