Search code examples
iosobjective-cautomatic-ref-countingnsnotificationcenter

observeValueForKeyPath: message sent to deallocated instance


I have a simple UIView child and I'm very confused as to why I'm getting this error (which causes the app to crash):

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

Here is the 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

Doesn't my dealloc ensure that a notification is never sent to a deallocated instance? How else can I prevent that from happening?

iOS 9, ARC enabled


Solution

  • You are mixing things up. The error is not caused by the NSNotificationCenter notification. Somewhere in your code you are using key-value observing and you do not remove that observer when the object is deallocated that is why your crash occurs.