How do I present a View Controller and dismiss all

2019-09-08 16:19发布

I have about 20 View Controllers, chained together with Modal and Push segues. Now, at the last View Controller I want to switch back again to the first View Controller, as if the user has restarted the app. Unfortunately when I do this with

[UIViewController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"InitViewController"]];
[self presentViewController:viewController animated:YES completion:nil];

all of the previous view controllers are not unloaded. Not a single viewDidUnload method is called. How can this be done?

2条回答
闹够了就滚
2楼-- · 2019-09-08 16:51

I found that it can be done easily by calling dismissViewControllerAnimated:completion: on the first view controller in the hierarchy. Fortunately that's all it is needed to accomplish what I wanted :-)

查看更多
Lonely孤独者°
3楼-- · 2019-09-08 16:56

The instantiateViewController method creates a new copy of your view controller. Your existing view controllers aren't unloaded because iOS doesn't know that you want to 'go back', so to speak. It can't unload any of your existing view controllers because they're still in the navigation hierarchy. What you really want to do is 'rewind' your storyboard in some way.

Fortunately from iOS 6 there's a much improved way to do this, through unwinding. This lets you 'backtrack' in your storyboard right back to the start, which it sounds like you want to do. The WWDC videos have some examples and walk throughs, and you might also want to look at this existing SO question:

What are Unwind segues for and how do you use them?

查看更多
登录 后发表回答