Right now the API doesn\'t seem to provide a way to detect if an observer has already been added for a particular NSNotification. What\'s the best way to avoid adding multi
The Upvoted answer with extension NotificationCenter { ... }
did not work for me, since my app was creating a new instance of a viewController (this had a Notification observer) every time a notification was posted, so removing an observer on a new instance of a viewController obviously doesn't work.
Previous instances of the viewController that had Notification Observers were getting called.
The below worked for me, since this was removing the Notification Observer as soon as the view was being disappeared.
// Notification observer added
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(self.someFunc(notification:)), name: Notification.Name("myNotification"), object: nil)
}
// Notification observer removed
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self, name: Notification.Name("myNotification"), object: nil)
}