RemoveObserver for Swift3 Notification

I have a strange problem. I register and cancel my notice like this:

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) } 

This view controller is located in the UITabBarController. doRegisterNotificationListener is called in viewDidAppear , and doUnregisterNotificationListener is called in viewDidDisappear . When I switch between tabs, the registration and unregister methods are called correctly (I tested using the print statement). However, if I run the notification, it will still be received, although doUnregisterNotificationListener was called last. Any ideas what I can do wrong here?

Quick note:

Also tried:

 NotificationCenter.default.removeObserver(self) 

This also does not work.

+5
source share
2 answers

I checked your code, and as soon as I register an observer with this type, it is not called when you register it. please try this.

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

If you are working with addObserver(forName:object:queue:using:) , you should remove it as follows:

Create:

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

Delete

 center.removeObserver(self.localeChangeObserver) 

This approach is taken from the documentation .

+1
source

Source: https://habr.com/ru/post/1265280/


All Articles