ios - NSNotificationCenter 偶发性崩溃

标签 ios nsnotificationcenter uicollectionviewcell

在我的 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/

相关文章:

ios - 为什么 NSNotificationCenter 发布会导致“无法识别的选择器发送到实例?”

ios - 自动调整 Collection View 单元格大小会忽略首次显示时的自动布局

ios - 具有多个单元模板的 CollectionView(使用未声明的类型,<typeName> 对于此上下文中的类型查找是不明确的)

ios - collectionView 中每个单元格的时间戳

ios - 苹果预发布应用提交 "Missing beta entitlement"

ios - Spotify 的 iOS SDK 教程出错

ios - 尺寸等级的色域到底是多少?

iOS/iPhone 可达性 - 如何仅在互联网丢失/无法使用 Reachability.m/.h 时检查

iOS 确认 UIAlertView 在 "Are you sure?"设置 App

ios - NSNotificationCenter Swift 3.0 在键盘上的显示和隐藏