Sunday, May 3, 2015

iOS Tutorial - Part 31 - NSNotificationCenter (Broadcasting an event)

NSNotificationCenter


Video Description 

In order to broadcast an event through the entire application, we can use NSNotificationCenter API. The usage is very simple, here are the steps: 1- Add (Register) the notification
[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(dismissAddVC)
                                                 name:@"CallDismissAddVC"
                                               object:nil];
2- Write the method that we want to be called
- (void)dismissAddVC
{
    //implementation of the method
}
3- Post (Broadcast) notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"CallDismissAddVC" object:nil];
4- Remove the observer
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"CallDismissAddVC" object:nil];
You should be careful not misuse NSNotificationCenter. For simple things like the app we created in this demo we better use delegate method, but for more complicated apps that you want to broadcast an event for more than 2 places, it's reasonable to use NSNotificationCenter.

Download

Download this App from HERE.

No comments:

Post a Comment