den330
den330

Reputation: 403

Do I need to remove observer manually if I want it to be there for the entire app life time?

My NSNotification Observer is not just for a certain view or view controller. I want it to be removed only when users close the app. I put the "add observer" in AppDelegate. Do I still need to remove it in deinit manually or it gets removed automatically when the app is closed?

Upvotes: 0

Views: 1139

Answers (4)

Vvk
Vvk

Reputation: 4043

Try this

you have to addobserver in didFinishLaunchingWithOptions

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(<#your selector#>)
                                                 name:@"TestNotification"
                                               object:nil];

    return YES;
}

then remove observer in applicationWillTerminate. you not need to remove observer in other methods because many times app going to background and not calling didFinishLaunchingWithOptions all time. so you have to remove in applicationWillTerminate only.

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    // If you don't remove yourself as an observer, the Notification Center
    // will continue to try and send notification objects to the deallocated
    // object.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

hope it helps you.

Upvotes: 1

Chandan
Chandan

Reputation: 757

I think, you should write your code in

 deinit{
   //remove observer here
}

Add above method in Appdelegate class.

Hope this will help you. Thanks

Upvotes: 1

VRAwesome
VRAwesome

Reputation: 4803

If you want notification for certain view controller then please add add observer to that particular classes and remove observer in viewDidDisappear. Ae seen your case, right now you have added add observer in app delegate , then you can remove it in below methods according to your requirements.

- (void)applicationWillResignActive:(UIApplication *)application 
- (void)applicationDidEnterBackground:(UIApplication *)application
- (void)applicationWillTerminate:(UIApplication *)application

Upvotes: 3

Saurabh Jain
Saurabh Jain

Reputation: 1698

When the app is terminate then a method call i.e.

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. 
}

you can remove the observer:

or you cal remove the observer here:

- (void)applicationDidEnterBackground:(UIApplication *)application
{

}

When application come in background.

Upvotes: 1

Related Questions