我無法理解object
參數是什麼NotificationCenter.default.addObserver(observer:selector:name:object)
NotificationCenter addObserver(observer:selector:name:object) - 什麼是對象?
如果我理解正確的話,它作爲一種過濾器;只有從這個對象發佈的通知纔會被觀察到。但我似乎無法真正弄清楚如何使用它。
我創建了一個類,並用它製成的全局實例
class FooClass {
func postNotification() {
NotificationCenter.default.post(name: NSNotification.Name("TestNotification"), object: self)
}
}
let globalFoo = FooClass()
然後在我的第一個視圖控制器我按下一個按鈕,它調用globalFoo.postNotification()
然後在我的第二個視圖控制器我註冊了,像這樣:
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
(即無),很顯然我誤解它是什麼。
我回滾上次編輯。不要編輯你的問題來顯示答案,只需接受一個答案(如你所見)。 – rmaddy