An NSNotificationCenter object (or simply, notification center) provides a mechanism for broadcasting information within a program. An NSNotificationCenter object is essentially a notification dispatch table.

Objects register with a notification center to receive notifications (NSNotification objects) using the addObserver:selector:name:object: or addObserverForName:object:queue:usingBlock: methods. Each invocation of this method specifies a set of notifications. Therefore, objects may register as observers of different notification sets by calling these methods several times.

When an object (known as the notification sender) posts a notification, it sends an NSNotification object to the notification center. The notification center then notifies any observers for which the notification meets the criteria specified on registration by sending them the specified notification message, passing the notification as the sole argument.

Add a Observer anywhere within a view, and this is how you add one:

[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(myHandler:)
                                      name:@"TESTING" object:nil];

Now, when a notification “TESTING” is broadcasted from anywhere within your program, and if you have successfully added the observer then the function “myHandler” will be called.
This is how you broadcast a notice:

[[NSNotificationCenter defaultCenter] postNotificationName:@"TESTING" 
                                      object:@"Pass any object here"];

And, you can also pass an object with it.
Below is a sample handler(myHandler in here):

-(void)myHandler:(NSNotification *)notice {
    NSString *str = [notice object];
    NSLog(@"%@",str);
    /* do what you want to do */ 
}

Don’t forget to remove the observer(probably in dealloc).

[[NSNotificationCenter defaultCenter] removeObserver:self];

Leave a Reply

*

Search