Where should I remove a notification observer?
Asked Answered
S

3

5

I set up a notification observer in my view controller's init method like so:

[[NSNotificationCenter defaultCenter] 
                    addObserver:self
                    selector:@selector(saveState)
                    name:UIApplicationWillResignActiveNotification
                    object:nil];

Where is the best place to call removeObserver:name:object: for this notification. I'm currently calling it in my dealloc method, but wanted to know if that might cause problems.

Schistosome answered 13/1, 2011 at 21:40 Comment(0)
L
8

No, you got it right. dealloc is the correct location to remove notification observers (unless you have some specific reason to need to remove the observer earlier).

Linger answered 13/1, 2011 at 21:43 Comment(2)
Thanks for this, nice to get confirmation.Schistosome
Could you please post a reference to the official documentation.Uncanonical
J
1

You can always remove the observer in viewWillDisappear:, or when you are done using it and have no other need for it, you can place it in a function.

Joceline answered 13/1, 2011 at 21:52 Comment(1)
Unless the view is going to appear again. I think your approach would work if I started the notification observer in viewWillAppear:.Schistosome
G
1

If the -saveState only need to execute once when active, then you can removeObserver inside the -saveState.

Gilles answered 14/1, 2011 at 1:46 Comment(3)
Presumably, he would want to save again if the app becomes active and then resigns active again.Linger
You are right. I assuem he will register as an observer again when the app become active.Gilles
I just used saveState as an example, but it would probably need to be called over and over again (for example when the app will enter the background) so I like using dealloc better.Schistosome

© 2022 - 2024 — McMap. All rights reserved.