Monday, December 28, 2015

Notification and Observers

A notification is a message sent to one or more observing objects to inform them of an event in a program. The notification mechanism of Cocoa follows a broadcast model. It is a way for an object that initiates or handles a program event to communicate with any number of objects that want to know about that event. These recipients of the notification, known as observers, can adjust their own appearance, behaviour, and state in response to the event. The object sending (or posting) the notification doesn’t have to know what those observers are. Notification is thus a powerful mechanism for attaining coordination and cohesion in a program. It reduces the need for strong dependencies between objects in a program (such dependencies would reduce the reusability of those objects). Many classes of the Foundation, AppKit, and other Objective-C frameworks define notifications that your program can register to observe.

The centrepiece of the notification mechanism is a per-process singleton object known as the notification centre (NSNotificationCenter). When an object posts a notification, it goes to the notification centre, which acts as a kind of clearing house and broadcast centre for notifications. Objects that need to know about an event elsewhere in the application register with the notification centre to let it know they want to be notified when that event happens. Although the notification centre delivers a notification to its observers synchronously, you can post notifications asynchronously using a notification queue (NSNotificationQueue).