miércoles, 14 de diciembre de 2011

Working with NSNotifications

Notifications are a great way to communicate with all the application, you can send just a message or add an object to the notification too.
The way it works is very simple, you need to post a notification with a name, for example if i want to let the project know my name, i could write :

  1. //Post notification
  2. [[NSNotificationCenter defaultCenter] postNotificationName:@"myNameIs"];

Right there you can see that NSNotificationCenter class has a defaultCenter. Commonly defaultCenter provides a singleton design pattern which has exactly one instance.
This way you'll use always the same object at memory, but how could the application knows my name if i'm not sending it?

You can also add an object to the postNotification method, for example in this case:

  1. //Now we add an object...
  2. [[NSNotificationCenter defaultCenter] postNotificationName:@"myNameIs" object:@"Nicolas Vidal"];

Gotcha! Now all the project should know my name, but... we need a way to listen to this notification.

So let's see that another ViewController is telling himself... "Which is his name?", so here come's the magic.

In the ViewController event, "ViewDidLoad" we must add an observer to that notification and a callback to receive that object.
So why ViewDidLoad? Because this event is called just when the View is loaded, remember that we need to add just ONE observer for each class/controller , and then remove our observer when we not need it
anymore.

  1. //Listen to notification
  2. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(knowHisName:) name:@"myNameIs" object:nil] ;

That way we need to implement the selector this way :
  1. -(void)knowHisName:(NSNotification *) nameNotification
  2. {
  3.    NSString *hisName = [nameNotification object];
  4.    NSLog("%@",hisName);
  5. }
We could observe that the NSNotification has an object, the same that we sent in postNotification, pretty simple, huh?

Now we need to remove the observer to not listen anymore to my notification :
  1. //Removing notification
  2. [[NSNotificationCenter defaultCenter] removeObserver:self name:@"myNameIs" object:nil];

That's all... now you can send messages through all the application with this amazing class.

No hay comentarios:

Publicar un comentario