observeValueForKeyPath:发送到释放实例的消息

observeValueForKeyPath: message sent to deallocated instance

我有一个简单的 UIView 子项,我很困惑为什么会收到此错误(导致应用程序崩溃):

[VideoView observeValueForKeyPath:ofObject:change:context:]: message sent to deallocated instance 0x13009b670

这里是 VideoView class:

@implementation VideoView

- (id)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(stopVideo)
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:nil];
    }
    return self;
}

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

//.. stopVideo method

@end

我的 dealloc 不能确保通知永远不会发送到已解除分配的实例吗?我还能如何防止这种情况发生?

iOS 9,启用 ARC

你把事情搞混了。该错误不是由 NSNotificationCenter 通知引起的。在您的代码中某处您正在使用 key-value observing 并且在对象被释放时您没有删除该观察者,这就是您发生崩溃的原因。