何時調用[[NSNotificationCenter defaultCenter] removeObserver:self];?

來源:互聯網
上載者:User

前一陣子在維護一個項目時看到以前同事寫的代碼,看到他把所有的[[NSNotificationCenter defaultCenter] removeObserver:self];方法都放到了viewController的dealloc方法中,添加observer放到了init中,當時並沒有想太多。

後來在寫相關代碼時發現,當某個notification被post之後,觀察者的方法被多次調用。於是想到,難道是多次添加了觀察者,而沒有刪除他?於是看了下蘋果官方文檔中的代碼,發現官方例子中是在viewWillAppear的時候添加,viewWillDisappear的時候remove。

文檔:

Discussion

Be sure to invoke removeObserver: or removeObserver:name:object: before notificationObserver or
any object specified inaddObserver:selector:name:object: is deallocated.

樓下 black_zero提供的網址中找到的一段文字:

This is also the reason why, when you go out of existence, you must unregister yourself from the shared notification center if you are registered there to receive any notifications (Chapter
11). If you registered using addObserver:selector:name:object:,
you handed the notification center a reference to yourself as the first argument; the notification center’s reference to you is a weak reference, as well it might be, since the notification center would have no business keeping you in existence, but this is
a non-ARC weak reference, and there is a danger that the notification center will try to send a notification to whatever is referred to, which, if it isn’t you (because you no longer exist), will be garbage. By unregistering yourself, you remove the notification
center’s reference to you, so there’s no chance it will ever again try to send you a notification.

寫了個例子(未開啟arc)實測,addobserver的確是弱引用,感謝black_zero的指正!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.