Notifications

Notifications are a mechanism for broadcasting a simple message throughout an application. A notification can be posted from anywhere, and any object instance can register for a notification that a message has been posted. Notifications work similar to radio signal station broadcasting on a specific frequency, and objects registered for a notification are like radios tuned to that frequency. As the analogy suggests, coupling between notification posters and listeners is minimal.

Adding observers and posting notifications are both done through a Singleton instance of NSNotificationCenter available through the NSNotification class method defaultCenter. A poster has no idea about the listener or number of listeners if a notification is raised, because the listeners register with NotificationCenter directly using the addObserver method. An object can stop receiving notifications at any time by sending a removeObserver message to NotificationCenter.

NSNotificationCenter allows small amounts of data to be piggybacked along with the notifications. There is a form of the post method that allows us to append dictionary defined by the user to the notification posted by the poster. This information is available to the observer through the userInfo property of the NSNotification parameter passed with the notifying callback:

- (void)postNotificationName:(NSNotificationName)aName object:(id)anObjectuserInfo:(NSDictionary *)aUserInfo;

As we mentioned, notification registration is done with an addObserver method call. There are two forms; one specifies a selector callback, as follows:

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSNotificationName)aName object:(id)anObject;

The other provides a block:

- (id<NSObject>)addObserverForName:(NSNotificationName)name  object:(id)obj  queue:(NSOperationQueue *)queue  usingBlock:(void (^)(NSNotification *note))block;

The first form takes the following arguments:

An Observing object and selector must be provided, but the name of the notification and sender object may be nil. If the notification name is nil, the selector will be called when any notification is posted; if the sender object is nil, the selector will be called regardless of which object posts the notification. Setting both to nil indicates an interest in observing all notifications.

The second form takes the following argument:

Other than a selector, the block to execute in response to the notification is provided. The queue allows you to specify an NSOperation queue to which the block will be added for execution. All parameters except the block may be nil, which would specify that the block should be run on the posting thread in response to any object posting any notification.