NSNotification Center iOS
NSNotification Center iOS Santiapps.com by Marcio Valenzuela
The idea behind this is to notify one object/class of another object/class’ action. Thus you need the following:

1. A Class (A) whose object will register to receive notifications (be notified).
2. A Class (B) whose object will be doing something and when it finishes, must notify the other (post notification)

Receiving Class A

This class must cleanup its listening task so that when it is no longer active, the NSNotificationCenter will not waste time and resources notifying it about events it was once interested in. To do this simply add this to your dealloc method:

//1. NSNotifCtr CLEANUP in viewDidUnload or dealloc
[[NSNotificationCenter defaultCenter] removeObserver:self];

This class must actually register or addObserver:self, (add itself as an observer) to those notifications, preferably at the start such as a viewDidLoad method:

//2. Register as observer of notifications in viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self

Now think of the NSNotificationCenter as this huge billboard which looks like this:

NSNotificationCenter Dispatch Table
Santiapps.com by Marcio Valenzuela

This class will eventually receive the notification so it must be able to handle it with a method such as this one:

//3. Method to prove notif received…
– (void) receiveTestNotification:(NSNotification *) notification
// [notification name] should always be @”TestNotification”
// unless you use this method for observation of other notifications
// as well.

if ([[notification name] isEqualToString:@”TestNotification”])
NSLog (@”Successfully received the test notification!”);

Now lets switch to the notifying class or Sending Class.

Sending Class B

This class must have a method that is responsible for doing something, like receiving the final downloaded data, or the parsing of a result or picking of an image or person. In such a method, which is the one you want to be responsible of notifying observers that a particular task is finished, you will have some generic code such as:

//4. Post notif to NSNotif in calling method OTHER CLASS
[[NSNotificationCenter defaultCenter]

This is the code that will post to the bulletin board when a task has finished!

Happy Notifying! ๐Ÿ™‚

Leave a Reply