gpt4 book ai didi

objective-c - 在 Dealloc 中删除观察者

转载 作者:搜寻专家 更新时间:2023-10-30 19:55:28 24 4
gpt4 key购买 nike

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.

我有一个对象,它通过 [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 调用时无效。

有什么想法吗?

最佳答案

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

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.

关于objective-c - 在 Dealloc 中删除观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7680550/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com