NSNotification
What is Notification
- It’s a message sent to one or more observing objects to inform them of an event in a program
- 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.
- A blind structured way of communication (notification doesn’t have to know what those observers are)
- A broadcast radio station model in MVC
- A very similar idea like the event listener model in Java
How does Notification work
- an object post a notification to notification center
- notification center broadcast the event
- event goes to the observer who registers itself at notification center
Benefit of Broadcast Model in Notification
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).
Get default notification
Each running Cocoa program has a default notification center. You typically don’t create your own.
Register at notification center
Register observer(yourself) at notification center if you want to listen to broadcast, In this example, we are listening to system broadcast(UIContentSizeCategoryDidChangeNotification)
Remove observer at notification center
Failure to remove yourself can sometimes result in crashers.
Reference
- Stanford iOS 7 development
- Mac Developer Library
- Cocoa Core Competencies