我有一個涉及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