Today we are learnign how to do work with notificationcenter So lest start
NSNotificationCenter provides a centralized hub through which any part of an application may notify and be notified of changes from any other part of the application. Observers register with a notification center to respond to particular events with a specified action. Each time an event occurs, the notification goes through its dispatch table, and messages any registered observers for that event. (Note: Each running Cocoa program manages its own default notification center, so it’s unusual for a new notification center to be instantiated separately.)
Each NSNotification object has a name, with additional context optionally provided by an associated object and userInfo dictionary.
For example, UITextField posts an NSNotification with the name UITextFieldTextDidChangeNotification each time its text changes. The object associated with that notification is the text field itself. In the case of UIKeyboardWillShowNotification, frame positioning and animation timing are passed in userInfo, while the notification’s associated object is nil.
Notifications classes
Foundation provides 3 classes to deal with all your notification
- NSNotification: represents a notification.
- NSNotificationCenter: broadcasts notifications and manages observers. Each app has a default notification center via defaultCenter.
- NSNotificationQueue: coalesces and delays notifications. Each thread has a default notification queue via defaultQueue.
OS X offers a fourth class called NSDistributedNotificationCenter for communication between processes.
Receiving notifications
To receive a notification you only need to know its name. Cocoa and Cocoa Touch are full of interesting and descriptively named notifications such as UIKeyboardWillShowNotification and UIApplicationDidReceiveMemoryWarningNotification.
- (id) init {
if (self = [super init]) {
_cache = [[NSCache alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidReceiveMemoryWarning:)
name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
}
return self;
}
- (void) applicationDidReceiveMemoryWarning:(NSNotification*)notification {
[_cache removeAllObjects];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIApplicationDidReceiveMemoryWarningNotification];
}
Handling the notification
Observers will receive notifications until they are removed from the NSNotificationCenter. Each notification is sent once per addObserver call. If you are receiving more notifications than expected, it might be a sign that you added the observer more than once (e.g., this might happen if you register the observer for notifications in viewWillAppear and unregister it in dealloc).
NSNotificationCenter will call the selector provided in addObserver:selector:name:object: with a single argument of type NSNotification. The selector is called in the same thread in which the notification was posted. Typically this is the main thread, so only check if the selector is running in a different thread if the corresponding documentation says otherwise.
- (void) moviePlayerPlaybackDidFinish:(NSNotification*)notification {
MPMoviePlayerController *mpObject = (MPMoviePlayerController *) notification.object;
NSDictionary *userInfo = notification userInfo;
MPMovieFinishReason reason = [[userInfo objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
}
Knowing the contents of this dictionary for a specific notification might require debugging or -god forbid- reading the documentation. Don’t assume that any particular key will be present unless told otherwise.
- (id) init {
if (self = [super init]) {
_cache = [[NSCache alloc] init];
_observer = [[NSNotificationCenter defaultCenter]
addObserverForName:UIApplicationDidReceiveMemoryWarningNotification
object:nil
queue:nil
usingBlock:^(NSNotification *notification) {
[_cache removeAllObjects];
}
];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:_observer
name:UIApplicationDidReceiveMemoryWarningNotification];
}
Sending synchronous notifications
Notifications are great to broadcast events that might be of general interest, such as model changes, user actions or the status of background processes. Unlike the delegate pattern, notifications can be used to notify various stakeholders and add very little coupling (in most cases, the observer only needs to know the notification name).
Posting the notification
Each app has a default NSNotificationCenter instance that can be used to broadcast notifications. You can create the notification object yourself and post it, or use a couple of convenience methods that do this. If you don’t need to send any additional information, posting a notification is as simple as:
[[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:notificationSender];
Sending additional information
In most cases you will want to send additional information with the notification, such as the progress value in the example above. Notifications can have a dictionary with custom data called userInfo. NSNotifcationCenter offers a convenience method to post notifications with userInfo:
NSDictionary *userInfo = @{@"someKey": someValue};
[[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:notificationSender userInfo:userInfo];
Download demo program from here