Let's say that on the tap of a UIButton
in ViewControllerA
the following happens before transitioning to ViewControllerB
:
- (IBAction)levelSelectButton:(id)sender {
ViewControllerB* obj = [[ViewControllerB alloc] init];
[self addChildViewController:obj];
CGSize screenSize = [MainScreen screen];
CGFloat screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;
obj.view.frame = CGRectMake(0,0,screenWidth,screenHeight);
[obj.view addSubview:_banner];
//[obj didMoveToParentViewController:self];
[self runPushAnimationWithController:obj];
}
When ViewControllerB
shows up, I can see my _banner
(a GADBannerView
object) view in place, but when I return to ViewControllerA
it is no longer there.
I have never used addChildViewController:
/didMoveToParentViewController:
methods before so I don't know if this is expected, but I want to be able to return to ViewControllerA
with _banner
still visible.
Do I need to retain it?
A view can only belong to a single superview. To quote Apple's docs:
Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.
So when you add your view to a newly created parent view controller, it gets removed from the current view controller's view hierarchy.
I would advise against doing this sort of thing. Just create a copy of the view in both places. If it uses large amounts of data, share the data (model) between view controllers, but not the view objects.
If you are completely set on moving your view around between view controllers, I would add a property to the new view controller and set that property rather than manipulating the other view controller's view hierarchy. You'll also have to pass the view BACK when you return to your current view controller.
You should treat a view controller's view hierarchy as private. Not doing that violates the principle of encapsulation.