How can I add and remove notification observers when a UIViewController is pushed/pulled by a navigation controller?
I usually add the UINotification
开发者_StackOverflow中文版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 ?
In order to get notified, you can set the delegate of the UINavigationController. This is quite cumbersome though, since the navigation controller only has one delegate. So in this case, I would have used viewDidAppear:animated
, viewDidDisappear:animated
and so on. These methods will be called on your view controllers as the navigation controller hides and shows them, and will also be called if you present a modal view controller in which case you probably also want to unregister notifications.
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.
You need to subclass UINavigationController to keep track of whether it is pushing or popping. Then in your viewWillAppear you can check to see if you're being pushed or popped. I have a subclass for that Here
精彩评论