NSNotificationCenter removeObserver not working
Here is how to do it in Swift 4...
private var observer: Any!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
observer = NotificationCenter.default.addObserver(forName: NSNotification.Name("SomeNotification"), object: nil, queue: nil) { notification in
//do something
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(observer)
}
From Apple Doc:
To unregister observations, you pass the object returned by this method to removeObserver:. You must invoke removeObserver: or removeObserver:name:object: before any object specified by addObserverForName:object:queue:usingBlock: is deallocated.
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self.localeChangeObserver];
You're trying to remove the worng observer, self
is not the observer here, the observer is the object returned by the add method