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

标签 iphone objective-c ios observer-pattern

我在 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/

相关文章:

iPhone 持久存储

ios - 如何使用 Swift 2.0 动态转换为在字符串中命名的类型?

IOS/objective-C :EventKit EKReminders compared with EKEvents

iphone - iPad 崩溃以及可能相关的内存问题

iphone - 向 Facebook 和 Google+ 好友发送邀请

ios - 更改 UICollecionViewCell 之间的空间

ios - Xcode 7 - 不兼容的 block 指针类型

iphone - 更改导航栏的颜色

ios - 应用程序使用的 iCloud 存储空间?

objective-c - 在 SpriteKit 中使用 SKLabelNode 插入换行符