我在 viewDidLoad
中使用 addObserver:selector:name:object:
。
我在 viewWillDisappear:animated:
中使用 removeObserver:name:object:
来移除观察者。
如果我通过将错误的参数传递给 removeObserver:name:object:
未能移除观察者,会发生什么情况?
(例如,如果我将错误的通知传递给参数 name
或将错误的对象传递给 object
或 Observer
,则不会删除观察者)
如果在调用 removeObserver:name:object:
后观察者仍然不是 nil,我可以发现移除观察者失败,因为将调用 notificationSelector。
但是如果观察者在调用removeObserver:name:object:
后变成了nil,我就不知道移除观察者是否失败了。
当观察者变为nil时,观察者会自动移除吗?
还是 NSNotificationCenter
的 notification dispatch table
越来越大,最终应用变慢了?
编辑
当我使用 UIViewController 对象的子类作为观察者时,在调用 ViewController 的 dealloc
后应用程序不会崩溃。
但是当我使用其他类的对象时,应用程序在对象的 dealloc
被调用后崩溃。
最佳答案
更新: 来自 -[NotificationCenter removeObserver:]
:
If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its
dealloc
method. Otherwise, you should call this method orremoveObserver:name:object:
before observer or any object specified inaddObserverForName:object:queue:usingBlock:
oraddObserver:selector:name:object:
is deallocated.
旧答案:
观察者不会被自动移除。来自 NSNotificationCenter 类引用:
Important: The notification center does not retain its observers, therefore, you must ensure that you unregister observers (using removeObserver: or removeObserver:name:object:) before they are deallocated. (If you don't, you will generate a runtime error if the center sends a message to a freed object.)
因此你应该调用
[[NSNotificationCenter defaultCenter] removeObserver:self];
在您的 dealloc
方法中,如果您不能 100% 确定之前没有删除观察者。
关于iphone - 当观察者变为零时观察者会自动移除吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11544690/