Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add and remove notification observers when a UIViewController is pushed/pulled by a navigation controller?

I usually add the UINotification observer in the init method and I remove them in dealloc.

However if I have a chain of UIViewControllers pushed by a UINavigationController, they are not deallocated when the next UIViewController is pushed. Consequently they all observe for the notification, and this is not what I want.

How can I add and remove notification observers when a UIViewController is pushed/pulled by a navigation controller ?

like image 218
aneuryzm Avatar asked Jan 18 '23 19:01

aneuryzm


1 Answers

Adding a second answer with an example on how to achieve this with a UINavigationControllerDelegate.

Somewhere, set the delegate to the root view controller. Either with code or by connecting it in a nib. Make your root view controller a UINavigationControllerDelegate.

@interface MyViewController : UIViewController <UINavigationControllerDelegate>
    // ...
@end

Do this in the implementation of the root view controller

@implementation MyViewController
- (void)navigationController:(UINavigationController *)navigationController 
      willShowViewController:(UIViewController *)viewController 
                    animated:(BOOL)animated
{
    [viewController
        performSelector:@selector(willBeShownViaNavigationController)];

    [navigationController.visibleViewController 
        performSelector:@selector(willBeHiddenViaNavigationController)];
}
@end

Make sure all the view controllers being used in that navigation controller implements those two methods.

Note: this code is untested, there may be some errors. But you should get the idea.

like image 99
August Lilleaas Avatar answered Apr 28 '23 08:04

August Lilleaas