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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With