Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNotification not being sent when postNotificationName: called

I'm trying to get one instance of using NSNotificationCenter with addObserver and postNotificationName but I can't work out why it won't work.

I have 2 lines to code to add the observer and send the message in 2 different classes

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

and

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

If I set the name to nil it works fine becuase it's just a broadcast, when i try and define a notification name the messages never get through.

like image 810
Affian Avatar asked Jan 21 '10 22:01

Affian


3 Answers

All my code makes use of NSNotifications like so:

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

[[NSNotificationCenter defaultCenter] postNotificationName:@"ScanCompleted" object:nil];

The first one is registering the notification and the second posting of the notification.

like image 93
James Avatar answered Nov 10 '22 16:11

James


Basically it's all to do with the order of execution. If you've executed postNotificationName before addObserver, then this is an easy problem to have. Use breakpoints and step through the code :)

Your first breakpoint should stop here:

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

Then here:

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

Also, make sure the selector has a colon on. Because it's method signature will be:

- (void)updateView:(NSNotification *)notification;
like image 34
PostCodeism Avatar answered Nov 10 '22 17:11

PostCodeism


I had the same problem. The reason is that I called removeObserver method at

- (void)viewDidDisappear:(BOOL)animated{

    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

   [notificationCenter removeObserver:self];

}

So check whether if you had called removeObserver before postNotification.

Tips: You can search the keyword "removeObserver" to find if you had called this function.

like image 8
Jia Xiao Avatar answered Nov 10 '22 15:11

Jia Xiao