Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If add an observer for a notification in the AppDelegate, do I need to bother removing it?

In the AppDelegate's didFinishLaunchingWithOptions:

[[NSNotificationCenter defaultCenter] addObserver:self 
                                      selector:@selector(contextChanged:)
                                      name:NSManagedObjectContextDidSaveNotification
                                      object:nil];

This is so I can merge changes to the data from other threads.

Question: Do I need to bother removing this listener in applicationWillResignActive or applicationWillTerminate? It doesn't seem like there's a point. I guess I'm asking if it's normal to have listeners like this in the main loop that never get removed.

like image 833
Jinyoung Kim Avatar asked Mar 05 '12 00:03

Jinyoung Kim


People also ask

Should I remove notification observer?

specifies. If your app targets iOS 9.0 and later or macOS 10.11 and later, and you used addObserver(_:selector:name:object:) , you do not need to unregister the observer. If you forget or are unable to remove the observer, the system cleans up the next time it would have posted to it.

How do I use notification observer in Swift?

First, register an observer for a notification with: addObserver(_:selector:name:object:) Then, post a notification with post(name:object:userInfo:) … … after which your selector is called. And don't forget to remove the observer with removeObserver()


1 Answers

You can never remove it, but if your app receive a notification (it won't happen in this case) while it is in background the notification will be queued and delivered to the application when it comes up again (if the app isn't killed ofc).

If don't want notifications that happen when your app is in background to be delivered once it comes up you can remove the listener in the methods you pointed out.

In this case, actually, it doesn't matter.

like image 64
fbernardo Avatar answered Oct 04 '22 17:10

fbernardo