Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 267
iOS Developer Avatar asked Sep 04 '16 09:09

iOS Developer


1 Answers

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

like image 173
Cristik Avatar answered Oct 23 '22 10:10

Cristik