iOS Developer
iOS Developer

Reputation: 187

Adding the same observer multiple times without removing it

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.

Upvotes: 11

Views: 5623

Answers (2)

Cristik
Cristik

Reputation: 32804

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

view lifecycle ios

Upvotes: 19

Zayne ZH
Zayne ZH

Reputation: 406

According to your code, not only will the selectors be triggered multiple times for every notification, it will continue consuming processing speed and battery life throughout the lifetime of your app until you remove it. If you want the observer to be able to be added by multiple actions, check if such an observer already exists then only add it if it doesn't.

Upvotes: 1

Related Questions