What will happen if I added an observer multiple times without removing it?
func registerForNotifications()
{
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(foregroundNotification(_:)), name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(backgroundNotification(_:)), name: UIApplicationWillResignActiveNotification, object: nil)
}
registerForNotifications()
will be called in viewWillApppear
.
Each call to addObserver:selector:notificationName:object:
will add a new entry to NSNotificationCenter
's dispatch table. Which means that multiple calls, even if made with the same argument list, will add multiple entries to that table. So, to answer your question, yes, registering multiple times for the same notification will result in your handler method to be called multiple times.
If you want to make sure you are not registering more than once, you will need to deregister your observer in the complementary tear down methods, see the diagram below to know where you should deregister, based on where you register (also I recommend reading the affiliate guide from the Apple documentation):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With