删除Dealloc中的Observer

时间:2011-10-06 21:17:00

标签: objective-c cocoa key-value-observing dealloc key-value-coding

  

已解决 - 事实证明,将nil传递给removeObserver:forKeyPath:会失败,但仅限于手动内存管理。它在垃圾收集模式下工作正常。 Apple文档并没有说它需要非零值,所以我认为这是一个错误。

我有一个对象,通过[self addObserver:self forKeyPath:等将自己添加为自身的观察者。在我的-dealloc方法中(注意我使用的是保留计数而不是垃圾收集器)我调用[self removeObserver:self forKeyPath:nil];这应该工作。但是,我收到以下错误:

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

现在,如果我删除该行以便它不会自行删除,我收到此消息:

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>
)

所以...对象正在观察自己......然而事实并非如此? :D注意在第二条消息中,观察者与被释放的实例具有相同的地址,因此它确实是同一个对象。

[self removeObserver:self forKeyPath:nil];在从-finalize调用时进行垃圾收集之前有效,但现在从手动托管代码中的-dealloc调用。

有什么想法吗?

1 个答案:

答案 0 :(得分:9)

关键路径应该是nil吗?来自Apple文档:

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

  

要观察的属性相对于接收器的关键路径。该值不得为零。