簡體   English   中英

removeObserver for Notification Swift3

[英]removeObserver for Notification Swift3

我有一個奇怪的問題。 我這樣注冊和取消注冊我的通知:

func doRegisterNotificationListener() {
        NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "RateAlertRated"), object: nil, queue: nil, using: rateDidRate)
    }

    func doUnregisterNotificationListener() {
        NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: "RateAlertRated"), object: nil)
    }

    func rateDidRate(notification: Notification) {
        let rating = notification.userInfo?["score"] as? Int
        let message = notification.userInfo?["message"] as? String
        let response = Response(rating: rating, message: message)
        output.presentRated(response)
    }

此視圖控制器位於UITabBarController中。 doRegisterNotificationListener被稱為viewDidAppeardoUnregisterNotificationListener被稱為viewDidDisappear 當我在選項卡之間切換時,正確調用了寄存器和取消注冊方法(我使用print語句進行了測試)。 但是,如果我發出通知,即使最后調用了doUnregisterNotificationListener ,仍會收到通知。 我在這里做錯了什么想法?

快速說明:

還嘗試過:

NotificationCenter.default.removeObserver(self)

這也行不通。

如果您正在使用addObserver(forName:object:queue:using:)您應該以這種方式刪除它:

創造:

let center = NSNotificationCenter.defaultCenter()
let mainQueue = NSOperationQueue.mainQueue()
self.localeChangeObserver = center.addObserverForName(NSCurrentLocaleDidChangeNotification, object: nil, queue: mainQueue) { (note) in
    print("The user's locale changed to: \(NSLocale.currentLocale().localeIdentifier)")
}

去掉:

center.removeObserver(self.localeChangeObserver)

這種方法取自文檔

我已經測試了你的代碼,一旦我注冊了這種類型的觀察者,當你取消注冊它時就不會調用它。 請試試這個。

NotificationCenter.default.addObserver(self, selector: #selector(rateDidRate(notification:)), name: Notification.Name(rawValue: "RateAlertRated"), object: nil)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM