Search code examples
nsnotificationcenterios8.1

Getting issue in NSNotificationCenter


NSNotificationCenter selector method is never called.

PostNotification is follow:

- (IBAction)go:(id)sender {
AnotherViewController *obj = [self.storyboard instantiateViewControllerWithIdentifier:@"AnotherViewController"];

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




[self.navigationController pushViewController:obj animated:YES];

}

Observe Notification in AnotherViewController.m:

  - (void)viewDidLoad {
[super viewDidLoad];

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


// Do any additional setup after loading the view.
  }

and receiveTestNotification is :

- (void) receiveTestNotification:(NSNotification *) notification
{


if ([[notification name] isEqualToString:@"TestNotification"])
    NSLog (@"Successfully received the test notification!");
 }

What is the problem? Thanks


Solution

  • You should move the add observer method to initialisation of the view controller. Because you are posting the notification before the AnotherViewController registers itself to receive the notification.

       - (instancetype)initWithCoder:(NSCoder *)aDecoder
        {
            self = [super initWithCoder:aDecoder];
            if (self) {
                [[NSNotificationCenter defaultCenter] addObserver:self
                                                         selector:@selector(receiveTestNotification:)
                                                             name:@"TestNotification"
                                                           object:nil];
            }
            return self;
        }