gpt4 book ai didi

iphone - 当观察者变为零时观察者会自动移除吗?

转载 作者:可可西里 更新时间:2023-11-01 06:22:21 24 4
gpt4 key购买 nike

我在 viewDidLoad 中使用 addObserver:selector:name:object:

我在 viewWillDisappear:animated: 中使用 removeObserver:name:object: 来移除观察者。

如果我通过将错误的参数传递给 removeObserver:name:object: 未能移除观察者,会发生什么情况?
(例如,如果我将错误的通知传递给参数 name 或将错误的对象传递给 objectObserver,则不会删除观察者)

如果在调用 removeObserver:name:object: 后观察者仍然不是 nil,我可以发现移除观察者失败,因为将调用 notificationSelector。

但是如果观察者在调用removeObserver:name:object:后变成了nil,我就不知道移除观察者是否失败了。

当观察者变为nil时,观察者会自动移除吗?
还是 NSNotificationCenternotification 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 or removeObserver:name:object: before observer or any object specified in addObserverForName:object:queue:usingBlock: or addObserver: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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com