jstm88
jstm88

Reputation: 3355

Removing Observer in Dealloc

SOLVED - it turns out that passing nil to removeObserver:forKeyPath: fails, but ONLY in manual memory management. It works fine in garbage collected mode. The Apple documentation does NOT say it requires a non-nil value so I'm assuming it's a bug.

I have an object that adds itself as an observer of itself, via [self addObserver:self forKeyPath: etc. In my -dealloc method (note that I am using retain counts and NOT the garbage collector) I call [self removeObserver:self forKeyPath:nil]; which should work. However, I get the following error:

Cannot remove an observer <Snapshot 0x10047a6d0> for the key path "(null)" from <Snapshot 0x10047a6d0> because it is not registered as an observer.

Now, if I remove that line so it doesn't remove itself, I get this message:

An instance 0x100193580 of class Snapshot was deallocated while key value observers were still registered with it. Observation info was leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger. Here's the current observation info:
<NSKeyValueObservationInfo 0x1001be2f0> (
<NSKeyValueObservance 0x1001a0a00: Observer: 0x100193580, Key path: fileURL, Options: <New: YES, Old: NO, Prior: NO> Context: 0x0, Property: 0x1001a02f0>
)

So… the object is observing itself… and yet it isn't? :D Notice in the second message, the observer has the same address as the instance being deallocated, so it is indeed the same object.

The line [self removeObserver:self forKeyPath:nil]; worked before when it was garbage-collected when called from -finalize but not now from -dealloc in manually managed code.

Any thoughts?

Upvotes: 3

Views: 3866

Answers (1)

Mattias Wadman
Mattias Wadman

Reputation: 11425

Should the key path really be nil? from Apple documentation:

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSKeyValueObserving_Protocol/Reference/Reference.html

The key path, relative to the receiver, of the property to observe. This value must not be nil.

Upvotes: 9

Related Questions