Post of NSNotificationCenter causing "EXC_BAD_ACCESS" exception

A UIViewController adds itself to the default center:

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

Then a UITableView delegate NSObject posts a NSNotification:

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

During run time it get a EXC_BAD_ACCESS exception.

Is the defaultCenter getting released somewhere? The same concept works when I post a notification to a UIViewController from a UIViewController, but that shouldn't matter, right?

Answers


One of your subscribers has been deallocated. Make sure to call [[NSNotificationCenter defaultCenter] removeObserver:self] in your dealloc (if not sooner).


EXC_BAD_ACCESS can happen even after verifying dealloc exists like so:

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self]
}

The above will solve the problem most of the time, but apparently my cause was that I was indirectly adding the observer with a selector: set to nil as follows:

[NSNotificationCenter.defaultCenter addObserver:self
                                         selector:nil
                                             name:notificationName
                                           object:nil];

...so when I posted something with that notificationName, EXC_BAD_ACCESS occurred.

The solution was to send a selector that actually points to something.


Need Your Help

Does NPM ignore files listed in .gitignore?

node.js git npm

I have a file that is generated by npm install command (using preinstall task). I don't want to add it in the git repository, nor in the NPM project.

How can non-determinism be modeled with a List monad?

haskell f# functional-programming monads non-deterministic

Can anyone explain (better with an example in plain English) what a list monad can do to model non-deterministic calculations? Namely what the problem is and what solution a list monad can offer.