Thursday, September 20, 2012

Use of NSNotificationCenter object to post and observe notification broadcasted within a program.

NSNotificationCenter is a class which helps to broadcast information within a program. Once the objects is register as a observer of a notification with a particular "notification_name' then every time the notification is posted with "notification_name" by any object, the active observer of that notification is notified. This simple post will show you how you can make use of NSNotificationCenter in your application.

Lets say PosterObject is our object and we want it to post notification with name "notice" and ObserverObject is our object and we want it to receive the notification with name "notice" broadcasted by any object in the program.

In your PosterObject.m file, from where you want to post your notification, this single line of code will handle all the broadcasting task for you.

[[NSNotificationCenter defaultCenter] postNotificationName:@"notice" 
                                      object:[NSString stringWithString:@"You are notified"];
This method will broadcast the notification with name "notice" along with string object so that the observer of the post will receive this string as well. You can add any other type of object with this post which you want the observer to receive.

Now, in your ObserverObject.m file, you can add this object as the observer of the notification with name "notice" using this single line of code.
[[NSNotificationCenter defaultCenter] addObserver:self 
                   selector:@selector(method_you_want_to_call:) name:@"notice" object:nil];
This method will register the object (self) to the NSNotificationCenter to be notified about the notification named "notice" and also sets the selector with the custom method method_you_want_to_callwhich will be invoked if the notification is observed.

The body of the method_you_want_to_callwill look like this
-(void) method_you_want_to_call:(NSNotification *) sentObject{

     //since the object sent was NSString
     NSString *string=(NSString *) [sentObject object] ;
     //Do your other stuffs after receiving the notification

Now include this in your project then compile and run your code. So if it should work all fine you should see a string "You are notified" printed in the console when ever the poster posts the notification and the observer is notified about the notification.

Suggestions and corrections are most welcome. If you have any, please do so without hesitation.

No comments:

Post a Comment