簡體   English   中英

哪個是刪除 Notification observer 的更好方法

[英]Which is a better way to remove Notification observer

我通常像下面的示例一樣使用 NSNotification:

在 viewDidLoad 中:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(foo:) name:kName1 object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bar:) name:kName2 object:nil];

在 viewDidUnload 和 dealloc 中:

[[NSNotificationCenter defaultCenter] removeObserver:self];

但是一個朋友告訴我,我不應該使用[[NSNotificationCenter defaultCenter] removeObserver:self]; 因為它將刪除所有觀察者,包括超類的觀察者。 他建議我使用下面的代碼來一個一個地移除觀察者。

[[NSNotificationCenter defaultCenter] removeObserver:self name:kName1 object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:kName2 object:nil];

我檢查了 ASIHttpRequest 庫的代碼( https://github.com/pokeb/asi-http-request )。 它遵循我朋友的建議。

我想知道我朋友說的對不對? 在我看來,既然當前實例會被unload或dealloc,超類的通知也是無用的。 還有系統UIViewController子類使用通知嗎?

你的朋友是 100% 正確的。 但是,刪除 dealloc 中的所有通知觀察並不重要。
你提到了viewDidUnload ,那里的情況完全不同,因為卸載的 object 將保持活着,你不知道什么時候再次添加超類的通知觀察。 如果將它們添加到 viewDidLoad 中,則不會有問題。 如果將它們添加到 init 方法中,您就會丟失一堆重要的通知觀察結果。

刪除具有特定名稱的觀察是一種很好的做法,應該從一開始就完成。

當你想刪除你使用的所有通知時,

[[NSNotificationCenter defaultCenter] removeObserver:self];

如果你想刪除你使用的特定通知,

[[NSNotificationCenter defaultCenter] removeObserver:self name:kName1 object:nil];

當您不再需要任何通知時,第一種方法很簡單。

由於 object 即將消失,因此可以安全地使用[[NSNotificationCenter defaultCenter] removeObserver:self]; dealloc方法中。

ViewDidUnload方法中,你最好一個一個地刪除每個觀察者,因為對 controller 的引用仍然存在(你相應的viewDidLoad應該將它們全部添加回來)。

我用的是第一種方式,從來沒想過對不對。 如果調用 dealloc,那么 object(也包括 super)無論如何都會被釋放。 您絕對不希望將 NSNotification 發送到已釋放的實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM