删除Dealloc中的Observer

Jus*_*kva 3 cocoa objective-c key-value-observing key-value-coding dealloc

解决的 -事实证明,传递nilremoveObserver:forKeyPath:失败,但只有在手动内存管理.它在垃圾收集模式下工作正常.Apple文档并没有说它需要非零值,所以我假设它是一个bug.

我有一个对象,它将自己添加为自身的观察者,通过[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.
Run Code Online (Sandbox Code Playgroud)

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

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>
)
Run Code Online (Sandbox Code Playgroud)

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

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

有什么想法吗?

Mat*_*man 9

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

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

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

  • removeObserver:forKeyPath:在GC下是可选的,因为KVO注册很弱.在手动引用计数下,它是未保留的.你确定这不是最重要的吗?传递nil作为keyPath听起来是假的,听起来你正在记住NSNotificationCenter的观察者删除方法的功能. (3认同)
  • 正如他提到的那样[敲定](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/finalize我认为他指的是在为Mac OS X构建时可用的垃圾收集 (2认同)