NSNotificationCenter selector not being called
Asked Answered
B

1

8

In my iPad app, in one class I register for a notification:

NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self selector:@selector(selectedList:) name:@"TTSelectedList" object:nil];

My selectedList: method looks like this:

- (void)selectedList:(NSNotification*)notification
{
    NSLog(@"received notification");
}

Then in another class (a UITableViewController) I post that notification when a row is selected:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"posting notification");
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TTSelectedList" object:nil];
}

I can confirm that the notification is being posted, because "posting notification" is logged to the console, but "received notification" is never called, meaning that the notification isn't received and the selector hasn't been called. I can't figure out what's causing this.

Thanks

Balkh answered 7/7, 2010 at 21:30 Comment(3)
Something stupid, but which left me puzzled for a while. I had the same issue. In my case, I didn't notice a subclass had method with the same selector as the one I was trying to declare in the parent class.Sensitize
Had this myself, also something stupid: I was posting a notification with a lowercase letter instead of a capital letter. They're case sensitive!Burnedout
In my case I created an object in local method, So the observer class dealloc during notification fire from another class. You can check this: #67328939Carvey
S
16

The most likely cause is that you're not actually calling addObserver:selector:name:object:. You don't have a logging line there; are you sure that code is running?

The second most likely cause is that you're calling removeObserver: before the notification is posted. This is most commonly in dealloc (which should always call removeObserver if you've ever observed anything). The error here would be that your observing object has deallocated before the notification.

Sombrous answered 7/7, 2010 at 21:37 Comment(4)
You were right, I was creating the object that was the observer in Interface Builder, and it wasn't being retained by anything. Thanks.Balkh
I had the same problem. I added the observer in the init method instead of initWithStyleYen
If you use IB to make your stuff, chances are that init will not get called. Use initWithCoder or awakeWithNib depending on what you want to do.Liebman
In my case issue with the local instance of listener class. Please check and vote if helps: #67328939Carvey

© 2022 - 2024 — McMap. All rights reserved.