removeObserver for Notification Swift3

时间:2017-03-10 11:08:27

标签: ios swift

我有一个奇怪的问题。我注册并取消注册我的通知:

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中调用viewDidAppear,在doUnregisterNotificationListener中调用viewDidDisappear。当我在选项卡之间切换时,正确调用了寄存器和取消注册方法(我使用print语句进行了测试)。但是,如果我发出通知,即使最后调用doUnregisterNotificationListener,仍会收到通知。我在这里做错了什么想法?

快速说明:

也尝试过:

NotificationCenter.default.removeObserver(self)

这也行不通。

2 个答案:

答案 0 :(得分:1)

如果您正在使用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)

此方法取自documentation

答案 1 :(得分:1)

我已经测试了你的代码,一旦我用这种类型注册观察者,当你取消注册它时就不会调用它。请试试这个。

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