在我的 iOS 应用程序中,我可以切换主题,以便立即在所有 View 之间切换主题,任何可见 View 都订阅了一个名为“updateTheme”的 NSNotificationCenter 通知,调用方式如下:
[[NSNotificationCenter defaultCenter] postNotificationName:@"updateTheme" object:self];
但是当我在一个带有自定义 Collection View 单元格的 View 中时,应用程序会在该单元格收到通知时崩溃。这是单元格中的所有代码:
- (void)didMoveToSuperview {
if (!isNew) {
isNew = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTheme) name:@"updateTheme" object:nil];
[self updateTheme];
}
}
- (void)updateTheme {
[UIView animateWithDuration:.5 animations:^{
self.titleLabel.textColor = [Colors boldText];
self.divider.backgroundColor = [Colors darkBorder];
} completion:^(BOOL finished){}];
}
当我注释掉单元格订阅通知的行时,应用程序运行正常。否则它会因这个错误而崩溃
-[__NSCFType updateTheme]: unrecognized selector sent to instance 0x1775d5d0
我不明白为什么会这样,如有任何帮助或建议,我们将不胜感激。
最佳答案
正如 matt 所指出的,我并没有在解除分配时作为观察者删除单元格,随后当通知被触发时对象消失了,所以应用程序崩溃了。为了修复它,我添加了这个:
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
关于ios - NSNotificationCenter 偶发性崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21666394/