68

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?

4

3 回答 3

131

您的一位订阅者已被解除分配。确保调用[[NSNotificationCenter defaultCenter] removeObserver:self]你的 dealloc(如果不是更早的话)。

于 2011-04-14T19:44:52.657 回答
11

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.

于 2014-10-13T06:10:00.883 回答
1

我在Swift中遇到了同样的问题。问题是函数目标有一个closure默认值的参数:

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

在我用参数替换closure参数后Notification,它起作用了:

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

我必须进行一些重构以使其以正确的方式工作。

于 2020-10-13T16:34:52.990 回答