Post of NSNotificationCenter causing "EXC_BAD_ACCESS" exception

Solution 1:

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

Solution 2:

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.

Solution 3:

I had the same issue in Swift. The problem was the function target had a closure parameter with default value:

@objc func performFoo(completion: (() -> Void)? = nil) {
   ...
}

After I replace the closure parameter with a Notification parameter, it worked:

@objc func performFoo(notification: Notification) {
    ...
}

I had to make some refactor to make it works in a right way.