简体   繁体   中英

When should I release the current UIViewController when transitioning to a new one?

I am trying to understand how to properly release the view controller I'm currently in during a transition to a new one. Here's my code:

// First create a CATransition object to describe the transition
CATransition *transition = [CATransition animation];
transition.duration = 0.3;
...

// Add the transition to the current view's superview
[self.view.superview.layer addAnimation:transition forKey:nil];

// Put together the controllers for the new screen
MainMenuController *menu = [[MainMenuController alloc] initWithNibName:@"MainMenuController" bundle:[NSBundle mainBundle]];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:menu];

// Transition
[self.view.superview addSubview:nav.view];
[self.view removeFromSuperview];

// These can now be released
[menu release]; // <- This works okay
[nav release];  // <- This causes problems

The problem theoretically makes sense to me. The variable menu is okay to release, because when I assigned it as the root view controller of my newly minted UINavigationController, the nav controller retained the menu. But I don't see anywhere that nav itself is potentially being retained, and sure enough, when I release as above, my UI goes all wonky. (It doesn't crash, but the entire menu UI is missing.)

I guess what I don't understand is when I'm expected to release nav. I mean, the view controller executing this code is not long for this world, so it can't do it. Where should I put the call?

You shouldn't do it this way, for the reasons you have discovered.

You need a third controller, up above the two you're transitioning, to hold the nav controller, so that controller 1 can deallocate itself.

[self.view.superview addSubview:nav.view]; 

I don't feel good with this code. I think you can tell your superView's controller do this task by using delegate or notification.

The superView contain nav.view, so its controller should also retain nav.view's controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM