Sam*_*fes 35 macos objective-c ios automatic-ref-counting
我有一个视图(我们称之为视图A),weak它的超级视图具有属性(视图B).查看KVO的超视图,视图B.由于视图A对视图B的引用是弱属性(为了防止保留周期),如何移除观察者(A观察B)?在我有机会删除之前,查看A对视图B的引用已经过了.
由于视图控制器具有对A的强引用,因此B比B更长.这是泄漏的日志消息:
An instance 0x9ac5200 of class UITableView 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 0x8660360> (
<NSKeyValueObservance 0x8660320: Observer: 0x8660020, Key path: contentOffset, Options: <New: YES, Old: NO, Prior: NO> Context: 0x8660020, Property: 0x864ac80>
)
Run Code Online (Sandbox Code Playgroud)
B是UITableView.设置断点会NSKVODeallocateBreak产生无用的结果.
在A的removeFromSuperview,我尝试删除观察者但是A对B参考已经nil.
更频繁地切换到unsafe_unretained手动操作或[A removeFromSuperview]在视图控制器中调用dealloc可以解决问题.我想知道如何使用weak属性来解决这个问题.
以下是相关代码:https://gist.github.com/2822776
您可以定义一个引用超级视图的显式弱属性,然后self使用像@"propertyReferringSuperview.propertyOfSuperview"?这样的关键路径进行观察。当您收到 KVO 通知时,您检查是否self.propertyReferringSuperview == nil并停止观察@"propertyReferringSuperview.propertyOfSuperview"。