iOS - clearing view controller stack from modal presentations

473 views Asked by At

Within my app, I have a button which appears on every view controller (the button is constant across all view controllers). When this button is clicked, it should bring the user to the initial view controller, essentially starting over.

When the button is clicked, it goes to the initial view controller fine, but the problem is that it keeps the stack of all the previous view controllers in memory. I'm not 100% certain, but this seems to be the case. If I keep going through the app, then click the button to restart, the app uses more and more memory every time I repeat this cycle.

Is there a way to clear the view controller stack from memory?

Here is the code (with only the relevant functionality) on how I am implementing the presentation. The button is included as the right bar button item in the navigation tab.

class CustomVC: UIViewController {

    override func viewDidLoad() {
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Start Over", style: UIBarButtonItemStyle.Plain, target: self, action: "goToInitialVC")
    }

    func goToInitialVC() {
        let initialVC: UIViewController = self.storyboard!.instantiateInitialViewController() as! UIViewController
        self.presentViewController(initialVC, animated: true, completion: nil)
    }

}
1

There are 1 answers

0
dstudeba On

This is the way I do it in my iOS app. Unfortunately I just realized yours is in Swift, mine is in Objective-C. Maybe it can still help.

in the AppDelegate.m

- (void)resetWindowToInitialView
{
    for (UIView* view in self.window.subviews)
    {
        [view removeFromSuperview];
    }

    UIViewController* initialScene = [initalStoryboard instantiateInitialViewController];
    self.window.rootViewController = initialScene;
}

In the other files

....
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate resetWindowToInitialView];

[self dismissViewControllerAnimated:YES completion:nil];
....