Reputation: 120324
Consider a UIViewController
whose view contains the view of another UIViewController
.
Is it correct to say that the parent UIViewController
is responsible to call the lifecycle methods of the child controller? Methods such as:
- (void)viewWillAppear:(BOOL)animated;
- (void)viewDidAppear:(BOOL)animated;
- (void)viewWillDisappear:(BOOL)animated;
- (void)viewDidDisappear:(BOOL)animated;
For example:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[_childViewController viewWillAppear:animated];
}
If so, which methods must be called?
Is there a better way to do this? Clearly the above approach is not forward-compatible: if a new lifecycle method is added the parent class needs to be modified to propagate the call of the new method.
Or is nesting view controllers simply a bad idea and should be avoided?
Upvotes: 0
Views: 332
Reputation: 532
If you want to create a hierarchy which still supports iOS 4, you would indeed need to forward the messages detailed in the documentation of the addChildViewController: yourself.
If iOS 4 is not targeted and you only need to build for ios 5 and later, stick with the new API as jrturton said.
Upvotes: 0
Reputation: 119242
The correct way to do this is to add the view controller as a child view controller. You need to maintain both a view hierarchy (adding the view as a subview) and a view controller hierarchy (adding the view controller as a child). All of the life cycle methods are then called for you.
The relevant methods are addChildViewController:
and didMoveToParentViewController:
.
There was a talk on view controller containment in WWDC 2011, I recommend watching the video.
Upvotes: 2