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

Usually I add a UINotification observer to the init method, and I delete them in dealloc.

However, if I have a UIViewControllers chain UIViewControllers on the UINavigationController , they are not released when the next UIViewController . Therefore, they all observe the notification, and that is not what I want.

How can I add and remove notification observers when the UIViewController pressed / pulled out by the navigation controller?

+4
source share
3 answers

To receive a notification, you can set a delegate from the UINavigationController. This is rather cumbersome as the navigation controller has only one delegate. So in this case, I would use viewDidAppear:animated , viewDidDisappear:animated and so on. These methods will be called on your view controllers when the navigation controller hides and shows them, and will also be called if you represent a modal view controller, in which case you probably also want to unregister notifications.

+4
source

Adding a second answer with an example of how to do this using UINavigationControllerDelegate.

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

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

Do this in the root view controller implementation

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

Ensure that all view controllers used in this navigation controller implement these two methods.

Note: this code has not been verified, there may be some errors. But you should get this idea.

+3
source

You need to subclass the UINavigationController to keep track of whether it clicks or pops up. Then, in your WillAppear view, you can check whether you clicked or clicked. I have a subclass for Here

+1
source

All Articles