肇鑫的技术博客

业精于勤,荒于嬉

苹果文档NotificationCenter中removeObserver(_:),讨论的部分是错误的

苹果的文档,在讨论中说:

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 this method or removeObserver(_:name:object:) before observer or any object specified in addObserver(forName:object:queue:using:) or addObserver(_:selector:name:object:) is deallocated.

这里很容易被认为是说,对于iOS 9.0和macOS 10.11以上的系统,开发者没有必要再手动移除观察器了。但是我测试的结果却并非如此。

小实验

view controllers 2

假设两个视图控制器的关系如上图所示。点击上面的视图控制器的Show按钮,会弹出下面的视图控制器,然后点击发送通知按钮,会发送一个通知。代码如下:

import Cocoa

class ViewController: NSViewController {
    static let foo = Notification.Name("foo")

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func postNotificationButtonClicked(_ sender: Any) {
        NotificationCenter.default.post(Notification(name: ViewController.foo))
    }
}
import Cocoa

class V2ViewController: NSViewController {
    private let a = 200

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(forName: ViewController.foo, object: nil, queue: nil) { [unowned self] (_) in
            
            print("foo!")
            self.run()
        }
    }
    
    deinit {
        print("V2ViewController deinit.")
    }
    
    private func run() {
        print(self.a)
    }
}

测试步骤

  1. 运行应用
  2. 点击Show按钮
  3. 点击Post Notification按钮
  4. 关闭弹出的窗口。此时控制台会显示V2视图控制器完全退出。
  5. 点击Post Notification按钮。
  6. Xcode提示应用崩溃,因为V2视图控制器已经从内存中销毁了。没有想应的实例。

小结

虽然苹果说对于iOS 9.0和macOS 10.11之后的系统,开发者不必手动移除观察器。但是实际上,如果不移除,那么该观察器就是一直存在的,并有可能造成程序崩溃。

这是因为,NotificationCenter.defaultNotificationCenter的静态属性,它一直在内存中存在。注册在它上面的观察器,因此也就一直在内存中存在。

解决

方法1

在deinit中手动移除观察器。

import Cocoa

class V2ViewController: NSViewController {
    private let a = 200
    private var observer:NSObjectProtocol!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        observer = NotificationCenter.default.addObserver(forName: ViewController.foo, object: nil, queue: nil) { [unowned self] (_) in
            
            print("foo!")
            self.run()
        }
    }
    
    deinit {
        if let observer = self.observer {
            NotificationCenter.default.removeObserver(observer)
        }
        
        print("V2ViewController deinit.")
    }
    
    private func run() {
        print(self.a)
    }
}

方法2

使用[weak self]替代[unowned self]。

import Cocoa

class V2ViewController: NSViewController {
    private let a = 200

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(forName: ViewController.foo, object: nil, queue: nil) { [weak self] (_) in
            
            print("foo!")
            self?.run()
        }
    }
    
    deinit {
        print("V2ViewController deinit.")
    }
    
    private func run() {
        print(self.a)
    }
}

这个方法只能避免应用的崩溃。其余的代码还是会执行。如果你有涉及到存储之类的操作,这种方式可能并不适合。

方法3

NotificationCenter.default文档中,苹果说:

All system notifications sent to an app are posted to the default notification center. You can also post your own notifications there.

If your app uses notifications extensively, you may want to create and post to your own notification centers rather than posting only to the default notification center. When a notification is posted to a notification center, the notification center scans through the list of registered observers, which may slow down your app. By organizing notifications functionally around one or more notification centers, less work is done each time a notification is posted, which can improve performance throughout your app.

我尝试自建一个NotificationCenter的实例。这么做的原理是,既然类属性会一直存在,那么我们就不使用类属性,而是使用实例。实例应该在V2视图控制器销毁时自动销毁。

import Cocoa

class ViewController: NSViewController {
    static let foo = Notification.Name("foo")
    private weak var center:NotificationCenter? = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func postNotificationButtonClicked(_ sender: Any) {
        center?.post(Notification(name: ViewController.foo))
    }
    
    override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
        if segue.identifier == "showV2Segue" {
            let v2 = segue.destinationController as! V2ViewController
            center = v2.center
        }
    }
}
import Cocoa

class V2ViewController: NSViewController {
    private let a = 200
    var center  = NotificationCenter()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        center.addObserver(forName: ViewController.foo, object: nil, queue: nil) { [unowned self] (_) in
            
            print("foo!")
            self.run()
        }
    }
    
    deinit {
        print("V2ViewController deinit.")
    }
    
    private func run() {
        print(self.a)
    }
}

我万万没想到,这个方案居然失败了。我本以为NotificationCenter的实例会自动释放。但是实际上并没有。查看苹果的文档。我发现这么一段:

The block is copied by the notification center and (the copy) held until the observer registration is removed.

块被复制到通知中心,(这个复制品)一直存在,知道观察器被移除。

因此,这个其实和closure导致的循环引用是类似的。

方法4

方法3失败了。不过苹果的说明,启发了我对于方法4的尝试。addObserver(_:selector:name:object:)是添加观察器的另外一个方法,它本身不复制块,而是发送消息给指定对象的函数。这个方式很Objective-C。因此,它需要@objc属性的函数。

import Cocoa

class V2ViewController: NSViewController {
    private let a = 200

    @objc fileprivate func extractedFunc() {
        print("foo!")
        self.run()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(extractedFunc), name: ViewController.foo, object: nil)
    }
    
    deinit {
        print("V2ViewController deinit.")
    }
    
    private func run() {
        print(self.a)
    }
}

这个方法才是符合苹果文档的描述的添加方式。
不过,从原理上讲。这个能够生效的原因,是因为addObserver(_:selector:name:object:)的第一个参数,即observer,它是将整个对象作为观察器,然后在需要时发送消息(第二个参数selector)给观察器。因此,当观察器(一般是当前的视图控制器)自动销毁时,就相当于给nil发送了一个消息。这种方式在Objective-C中是允许的,什么事情也不会发生。从理论上讲,这个其实是一种更安全的方法2。

方法5

搞懂了方法4,我们现在可以改进方法2。方法5,改进了方法2。能够达到方法4类似的结果。不过我们要始终记得,无论是方法2还是方法5,只要不采用方法1的方式移除观察器,那么被复制的块就会一直在等待被执行。

import Cocoa

class V2ViewController: NSViewController {
    private let a = 200

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(forName: ViewController.foo, object: nil, queue: nil) { [weak self] (_) in
            
            guard let strongSelf = self else { return }
            
            print("foo!")
            strongSelf.run()
        }
    }
    
    deinit {
        print("V2ViewController deinit.")
    }
    
    private func run() {
        print(self.a)
    }
}

总结

综合苹果的文档和实际测试的结果。不难发现,苹果文档存在错误。总结如下:

  1. 对于addObserver(_:selector:name:object:)添加的观察器。如果是iOS 9.0,macOS 10.11以后的系统,无需用户手动移除观察器。
  2. 对于addObserver(forName:object:queue:using:)添加的观察器。需要使用方法1或方法2的方法来解决。推荐使用方法1。
  3. 对于removeObserver(_:)文档。苹果的讨论是错误的。
  4. addObserver(_:selector:name:object:)的优点是不用手动注销观察器,缺点是需要单独创建一个函数,并且该函数必须是@objc的动态函数。
  5. addObserver(forName:object:queue:using:)的优点是无需单独创建函数,运行代码与添加代码紧密相连。缺点是每个控制器都需要单独用类变量记录下来,并且需要手动移除。(建议在deinit函数中移除)
  6. 综上,我认为方法4的方案是目前代价最小的方案。方法1是最完善的方案。方法5是最偷懒的方案。