-
Notifications
You must be signed in to change notification settings - Fork 4
NsNotification
iOS comes with a “Notification Center”, a centralized singleton object that allows objects to post notifications as well as to be notified when notifications are posted.
To publish a notification, call
[[NSNotificationCenter defaultCenter] postNotificationName:object:userInfo:(NSDictionary *)userInfo];To listen to it:
addObserver:selector:name:object:The selector specified will be called with an NSNotification in argument, you can access the notification publisher using NSNotification object properties and the userInfo dictionary from NSNotification userInfo properties.
This is the most flexible pattern and the one with the least amount of coupling. A notification consists of a NSString identifier and a NSDictionary to pass data along with it. The same notification can be posted by different objects, the notification is broadcasted to any object that is interested in it. With this pattern the event publisher and the event receiver don't have to know anything at all about each other.
This patterns works very well to publish global events, when it is difficult to keep track of all the components that needs to be notified of it. Model -> View Controllers, View Controller -> ViewControllers.
- powerful, flexible
- multiple objects can subscribe to the same event
- multiple objects can publish the same event
- asynchronous, you just queue notifications
- notifications can be coalesced
- Don't forget to unregister!
- Relies on NSString to identify notifications (no compile time check you are subscribing to an existing notification)
- passing data around in a dictionary, creating, reading it can be tideous and time consuming (boxing/unboxing).
- performance (previous comment)
- It is a one way communication, publisher does not know or care if anyone received it.
Unregister!
-(void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}otherwise: crashes, memory leaks, headaches, etc...
Switch to main thread if needed!
The notification callback runs in the same thread the notification was posted.
Cocoa uses the notification center to broadcast various system wide events (device orientation changes, network reachability changed, battery state, etc...);
- kReachabilityChangedNotification
- UIDeviceOrientationDidChangeNotification
- UIDeviceProximityStateDidChangeNotification
- UIDeviceBatteryLevelDidChangeNotification
- UIDeviceBatteryStateDidChangeNotification
- UIKeyboardDidShowNotification
- UIKeyboardWillHideNotification
- etc...