[英]How to readd a notification observer
因此,我在特定視圖 controller 中添加了大約四個通知觀察者,但我想在滿足條件時刪除一個,然后將其添加回來以適應不同的條件。 我能夠刪除特定的觀察者,但我無法將其添加回來。 其他的工作,除了一個刪除並添加回來,我知道它在加載 VC 並添加所有通知觀察者時工作,但是在添加回來后它停止工作。 這是我的代碼:
// registered the observer in ViewDIdAppear and this registers my bluetooth device and whenever i tap on the bluetooth device button this function gets called
NotificationCenter.default.addObserver(
self, selector: #selector(Myclass.deviceTapped), name: Notification.Name("bluetoothRecievedNoticicationName"), object: nil)
// i removed the observer here
if condition == false {
NotificationCenter.default.removeObserver(self, name: Notification.Name("bluetoothRecievedNoticicationName"), object: nil)
}
// and then use this to add it back again
NotificationCenter.default.addObserver(
self, selector: #selector(Myclass.deviceTapped), name: Notification.Name("bluetoothRecievedNoticicationName"), object: nil)
// and after adding this ^ back the deviceTapped function doesn't get called anymore
在這些情況下要做的事情是向自己證明這通常有效。 這樣,您可以跟蹤您正在做的事情,這會阻止它工作。
例如,也許self
在任何通知有機會到達之前就已經不存在了......? 也許您未顯示的其他代碼正在再次注銷您...? 我當然經歷過這樣的困惑。 而且它們可能很難調試。
但無論解釋如何,您首先需要向自己保證,取消注冊通知然后重新注冊是沒有問題的。
這是一個測試應用程序。 它具有三個按鈕:注冊、取消注冊和通知。 這是代碼:
let notif : Notification.Name = .init("howdy")
@objc func gotNotified() {
print("got notified")
}
@IBAction func doRegister(_ sender: Any) {
NotificationCenter.default.addObserver(self, selector: #selector(gotNotified), name: notif, object: nil)
}
@IBAction func doUnregister(_ sender: Any) {
NotificationCenter.default.removeObserver(self, name: notif, object: nil)
}
@IBAction func doNotify(_ sender: Any) {
NotificationCenter.default.post(name: notif, object: nil)
}
因此,在連接按鈕的情況下對其進行配置,然后:
點擊注冊。
點擊通知。
點擊取消注冊。
點擊通知。
點擊注冊。
點擊通知。
您會看到在 2 和 6,但不是 4,我們打印到控制台以證明我們已收到通知 - 正如您所期望的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.