0

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)
  • Quick question: what does your navigation look like? Is it like a next / previous scheme, or tabs at the bottom etc.? – m_katsifarakis Dec 28 '18 at 16:19
  • The first VC is a homescreen - so it has buttons such as continue game, new game etc, the second VC is level 1 and you return to the first VC by swiping upwards. I noticed an issue when I would press continue to return to the second VC and timer started counting down twice as fast (the timer value is a global function so I am assuming two instances of the second VC are causing this) – GarrisRyder Dec 28 '18 at 16:25
  • 1
    timers should be invalidated in `viewDidDisappear` – Shehata Gamal Dec 28 '18 at 16:27

1 Answers1

1

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

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87