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 removeObserver(_:name:object:) before observer or any object passed to this method is deallocated.

iOS 9.0 和 macOS 10.11 以后不需要手动移除观察者。

但在用 Block 形式添加观察者时,即 addObserver(forName:object:queue:using:),却遇到了崩溃的问题,因为观察者并没有被移除,查了下文档,在 addObserver(forName:object:queue:using:) 的文档中看到:

To unregister observations, you pass the object returned by this method to removeObserver(😃. You must invoke removeObserver(😃 or removeObserver(_:name:object:) before any object specified by addObserver(forName:object:queue:using:) is deallocated.

也就是说 Block 形式的观察者必须要手动移除。

addObserver(forName:object:queue:using:) 是有返回值的,是 NSObjectProtocol 类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var objectProtocol: NSObjectProtocol!

// ...

objectProtocol = NotificationCenter.default
.addObserver(forName: UIApplication.keyboardWillShowNotification,
object: nil,
queue: OperationQueue.main)
{ (notification) in
// ...
}

// ...

deinit {
NotificationCenter.default.removeObserver(objectProtocol!)
}

参考