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

NotificationCenter addObserver(observer:selector:name:object) -- what is object?

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

中的含义

如果我没理解错的话,它是一种过滤器;只有从该对象发布的通知才会被观察到。但我似乎无法真正弄清楚如何使用它。

我创建了一个 class 并制作了它的全局实例

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

let globalFoo = FooClass()

然后在我的第一个 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")
    }

}

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

发布通知时使用的object参数是为了表明实际发布通知的对象。

添加观察者时,您可以保留 object nil,您将收到所有指定的通知,而不管实际发送通知的是哪个对象。或者您可以在添加观察者时指定一个特定对象,然后您将仅在该特定对象发布命名通知时收到通知。

一些通知使用此参数向 observer 提供更合适的信息。

例如,像 NSManagedObjectContextObjectsDidChange 这样的通知可以选择接受 NSManagedObjectContext 对象,这样它就可以仅从该上下文中通知更改。