前一陣子在維護一個項目時看到以前同事寫的代碼,看到他把所有的[[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的指正!