NotificationCenter addObserver(observer:selector:name:object) -- 什么是对象?

MH1*_*175 1 ios notificationcenter swift

我无法理解object参数的 含义NotificationCenter.default.addObserver(observer:selector:name:object)

如果我理解正确,它就像一种过滤器;只会观察到从此对象发布的通知。但我似乎无法真正弄清楚如何使用它。

我创建了一个类并为其创建了一个全局实例

class FooClass {
    func postNotification() {
        NotificationCenter.default.post(name: NSNotification.Name("TestNotification"), object: self)
    }
}

let globalFoo = FooClass()
Run Code Online (Sandbox Code Playgroud)

然后在我的第一个 ViewController 我按下一个按钮 globalFoo.postNotification()

然后在我的第二个 ViewController 中,我像这样注册:

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived), name: NSNotification.Name("TestNotification"), object: globalFoo)

    }

    func notificationReceived() {
        print("notification received")
    }

}
Run Code Online (Sandbox Code Playgroud)

当我不指定object(即 nil)时它工作正常,所以很明显我误解了它是什么。

rma*_*ddy 5

object发布通知时使用的参数是指示实际发布通知的对象。

添加观察者时,您可以保留objectnil,无论哪个对象实际发送通知,您都将获得所有命名通知。或者,您可以在添加观察者时指定特定对象,然后只有在该特定对象发布指定通知时才会收到通知。