Swift NotificationCenter删除观察者最快的方法

Dee*_*rma 0 nsnotificationcenter ios swift

我在我加入了一些观察家的viewController- applicationWillResignActiveapplicationDidEnterBackground和许多其他。我想以self观察者的身份删除一行中的所有已注册通知。我的问题是,下面的代码行是否足以完成此操作,或者此代码是否存在问题?

deinit {
   NotificationCenter.default.removeObserver(self)
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*unt 10

所以我现在正在一个应用程序中处理这个问题,答案可能并不那么简单。

在文档中,它确实声明对于 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:) 
Run Code Online (Sandbox Code Playgroud)

最好的通用方法是捕获数组中的标记,在添加观察者时附加它们,并在 deinit/dealloc 或其他需要删除对象的观察者行为时使用它们进行删除。

在您的 VC/对象属性中创建一个数组来存储观察者“令牌”

var notifObservers = [NSObjectProtocol]()
Run Code Online (Sandbox Code Playgroud)

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

let observer = NotificationCenter.default.addObserver(forName: , object: , queue:) { [weak self] notification in
    // do a thing here
}
notifObservers.append(observer)
Run Code Online (Sandbox Code Playgroud)

移动

for observer in notifObservers {
    NotificationCenter.default.removeObserver(observer)
}
notifObservers.removeAll()
Run Code Online (Sandbox Code Playgroud)


Sh_*_*han 6

NotificationCenter.default.removeObserver(self)
Run Code Online (Sandbox Code Playgroud)

只要将所有这些都添加到

NotificationCenter.default.addObserver
Run Code Online (Sandbox Code Playgroud)


pbe*_*ery 5

@Sh_Khan是正确的:

NotificationCenter.default.removeObserver(self)
Run Code Online (Sandbox Code Playgroud)

Apple文档中所述,您甚至可以走得更远:

如果您的应用程序针对iOS 9.0和更高版本或macOS 10.11和更高版本,则不需要在其dealloc方法中注销观察者。