Search code examples
iosswiftnsnotificationcenternsnotifications

Multiple NSNotifications received in parent UIViewController


I have a parent UIViewController BaseViewController that I use for some views :

class TestViewController: BaseViewController { ...

I want to receive a notification in BaseViewController so I add an observer in its ViewWillAppear:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BaseViewController.receivedNotification(_:)), name:"NotificationIdentifier", object: nil)

I can't remove an observer on ViewWillDisappear because notification is sent from presented UIViewController that can be presented on every UIViewController with parent BaseViewController so BaseViewController is always disappeared.

So after navigating through the app there is more than one observer add and I receive notification multiple times.

What should I do to perform notification selector only once? Or how to .removeObserver when another UIViewController pushed(but do not remove when presented)?


Solution

  • You can very well use:

    NSNotificationCenter.defaultCenter().removeObserver(observer: <The class from which you want to remove>, name: "Name of notification which you want to remove", object: nil)