简体   繁体   中英

How to manage instantiated viewControllers

To summarise, how best is it to manage VC's?

In my case, I have 3 VC's in my game. To switch between them a button in the present VC activates the following code:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier:"firstLevel")
self.present(viewController, animated: false, completion: nil)

This code works, but each time it instantiates a new VC which causes issues in my game for global variables such as "Score" when there are two copies of the same VC and Im assuming this is really bad for memory also.

What is the best solution to this problem?

Should I dismiss the present viewController by placing the following line of code after I have instantiated the next VC?:

self.dismissViewControllerAnimated(false, completion: nil)

You need to have only 1 vc by replacing rootViewController

 let viewController = storyboard!.instantiateViewController(withIdentifier:"firstLevel")
(UIApplication.shared.delegate as! AppDelegate).window!.rootViewController = viewController 

As your current code leaves old vcs in the stack which for sure will cause memory issues

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