是否应该覆盖 deinit 以删除 Swift 中的观察者?

Should deinit be overridden to remove observers in Swift?

队友编写的代码如

deinit {
    NotificationCenter.default.removeObserver(self)
}

我评论删除它,因为框架已经照顾到观察者。如果没有副作用,队友希望保留此代码。现在,即使我们保留上面的代码会有任何副作用吗?

我是否也应该在 deinit 中调用 super.deinit()

是的,覆盖有效

deinit()

正如评论中指出的那样。不需要调用 Super。我在苹果文档中证实了这一点。

在我看来,明确清理是个好主意。特别是涉及到线程、通知和计时器时。

从 iOS 9 开始,如果您不使用基于块的观察者,则无需自己删除观察者。系统会为你做这件事,因为它在可能的情况下为观察者使用归零弱引用。

If the observer is able to be stored as a zeroing-weak reference the underlying storage will store the observer as a zeroing weak reference, alternatively if the object cannot be stored weakly (i.e. it has a custom retain/release mechanism that would prevent the runtime from being able to store the object weakly) it will store the object as a non-weak zeroing reference. This means that observers are not required to un-register in their deallocation method.

Block based observers via the -[NSNotificationCenter addObserverForName: object: queue: usingBlock] method still need to be un-registered when no longer in use since the system still holds a strong reference to these observers.

Apple Docs

而对于 super.deinit() 苹果说

Deinitializers are called automatically, just before instance deallocation takes place. You are not allowed to call a deinitializer yourself. Superclass deinitializers are inherited by their subclasses, and the superclass deinitializer is called automatically at the end of a subclass deinitializer implementation. Superclass deinitializers are always called, even if a subclass does not provide its own deinitializer.

swift docs