Swift NotificationCenter 移除观察者的最快方式

Swift NotificationCenter remove observer quickest way

我在我的 viewController -- applicationWillResignActiveapplicationDidEnterBackground 和许多其他人中添加了一些观察者。我想在一行中删除 self 作为所有已注册通知的观察者。我的问题是以下行是否足以做到这一点,或者此代码是否存在问题?

deinit {
   NotificationCenter.default.removeObserver(self)
}

NotificationCenter.default.removeObserver(self)

这一行足以去掉vc观察只要全部加上

NotificationCenter.default.addObserver

@Sh_Khan 是对的:

NotificationCenter.default.removeObserver(self)

你可以走得更远,如Apple Documentation中所述:

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.

所以我现在正在一个应用程序中使用它,答案可能不会那么简单。

在文档中,确实声明对于 iOS 9 及更高版本,您不再需要在对象的 deinit/dealloc 方法中显式删除观察者。 https://developer.apple.com/documentation/foundation/notificationcenter/1413994-removeobserver

但是,这似乎仅适用于基于选择器的通知观察器。我将引用此博客 post:https://oleb.net/blog/2018/01/notificationcenter-removeobserver/

如果您使用基于块的观察器,您仍然必须手动删除观察器。

addObserver(forName:object:queue:using:) 

执行此操作的最佳通用方法是捕获数组中的标记,在添加观察者时追加它们,并在 deinit/dealloc 或需要为对象移除观察者行为时使用它们进行删除.

在您的 VC/object 属性中创建一个数组来存储观察者 'tokens'

var notifObservers = [NSObjectProtocol]()

通过捕获函数 return 对象并将其存储为令牌来注册基于块的通知

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()