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 :
- //Post notification
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:
- //Now we add an object...
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.
- //Listen to notification
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(knowHisName:) name:@"myNameIs" object:nil] ;
That way we need to implement the selector this way :
- {
- NSLog("%@",hisName);
- }
Now we need to remove the observer to not listen anymore to my notification :
- //Removing notification
That's all... now you can send messages through all the application with this amazing class.
No hay comentarios:
Publicar un comentario