我在viewController
-applicationWillResignActive
,applicationDidEnterBackground
等许多人中添加了许多观察者。我想删除self
作为一行中所有已注册通知的观察者。我的问题是,下面的代码行是否足以完成此操作,或者此代码是否存在问题?
deinit {
NotificationCenter.default.removeObserver(self)
}
答案 0 :(得分:4)
是
NotificationCenter.default.removeObserver(self)
此行足以删除vc观测值,只要将所有内容添加到
NotificationCenter.default.addObserver
答案 1 :(得分:4)
@Sh_Khan是正确的:
NotificationCenter.default.removeObserver(self)
您可以走得更远,如Apple Documentation所述:
如果您的应用程序针对iOS 9.0和更高版本或macOS 10.11和更高版本,则无需在其dealloc方法中注销观察者。
答案 2 :(得分:0)
所以我现在正在应用程序中使用它,答案可能并不那么简单。
在文档中确实指出,对于iOS 9及更高版本,不再需要在对象的deinit / dealloc方法中显式删除观察者。 https://developer.apple.com/documentation/foundation/notificationcenter/1413994-removeobserver
但是,看来这仅适用于基于选择器的通知观察者。我将引用此博客文章:https://oleb.net/blog/2018/01/notificationcenter-removeobserver/。
如果您使用的是基于块的观察者,则仍必须手动删除观察者。
addObserver(forName:object:queue:using:)
执行此操作的最佳通用方法是捕获数组中的标记,在添加观察者时将其追加,并在初始化/解除分配时使用它们进行删除,否则需要删除对象的观察者行为。
在VC /对象属性中创建一个数组来存储观察者“令牌”
var notifObservers = [NSObjectProtocol]()
通过捕获函数返回对象并将其存储为令牌来注册基于块的通知
let observer = NotificationCenter.default.addObserver(forName: , object: , queue:) { [weak self] notification in
// do a thing here
}
notifObservers.append(observer)
删除
for observer in notifObservers {
NotificationCenter.default.removeObserver(observer)
}
notifObservers.removeAll()