我有一个涉及ARC,NSNotificationCenter和块的奇怪情况。以下是代码的简单示例。从测试看来,didSaveObserver
的存储器管理似乎是按照需要执行的,即它不创建保留周期,并且它在removeObserver:
之前不是nil
。防止弱分配的变量被释放而不创建保留周期
但是,我对ARC的理解让我觉得这只是一种侥幸/怪癖,ARC可以在removeObserver:
之前nil
didSaveObserver
。看到didSaveObserver
永远不会被保留(唯一的分配是一个0变量),那么ARC可以/(应该?)立即释放它。
我是否正确理解ARC规则?如果是这样,那么我如何确保didSaveObserver
被保留,以便它可以不被观察,但不创建保留周期?
self.willSaveObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSManagedObjectContextWillSaveNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
id preSaveState = ...; //Store some interesting state about a Core Data object (the details aren't significant to this question).
__weak __block id didSaveObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSManagedObjectContextDidSaveNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
//Unobserve the did save block. This is the tricky bit! didSaveObserver must be __weak to avoid a retain cycle, but doing so also means that the block may be dealloced before it can be unobsered.
[[NSNotificationCenter defaultCenter] removeObserver:didSaveObserver];
id postSaveState = ...;
//Perform work that uses pre & post save states.
}];
}];
更多细节:
如果__weak
不添加(所以默认为__strong
)仪器报告说,有一个保留周期。
我认为它创建了一个保留周期,因为乐器说它有。我已经更新了这个问题。 – 2013-04-23 11:20:38