How to pass object with NSNotificationCenter

Hi,
There are so many reason to use NSNotification. Now i am writing about how to use NSNotificationCenter in iOS.

First make 2 methods in ViewController.

- (void)registerNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"myNotification" object:nil];
}
- (void) receiveNotification:(NSNotification *) notification
{
    if ([[notification name] isEqualToString:@"myNotification"])
        NSLog (@"Successfully received the test notification!");
}

in ViewWillAppear Call registerNotification method

-(void)viewWillAppear:(BOOL)animated{
   [self registerNotification];
 }

Now, you can call myNotification from any ViewController by using below code,

[[NSNotificationCenter defaultCenter]postNotificationName:@"myNotification" object:self];
 

If you want to pass data into notification, You’ll have to use the “userInfo” variant and pass a NSDictionary object.

NSDictionary* userInfo = @{@"Name": @(@"Ashutosh Kumar")};
NSNotificationCenter* notify = [NSNotificationCenter defaultCenter];
[notify postNotificationName:@"myNotification" object:self userInfo:userInfo];

and need some change in receiveNotification method

- (void) receiveNotification:(NSNotification *) notification
{    if ([[notification name] isEqualToString:@"myNotification"])
        NSDictionary* userInfo = notification.userInfo;
        NSString* GetName = userInfo[@"Name"];
        NSLog (@"Successfully received test notification! %@", GetName);
}

That’s It. If you like this post, Please comment below or subscribe this blog. Leave your comments

Advertisements