1

I have a side menu in my iOS app with several entries. Once I click on one of them, I want to segue to the corresponding view controller via pushing them onto the navigation stack. This is currently done in the following way:

// Called on click event on table cell
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.tableView.deselectRow(at: indexPath, animated: true)

    // navigate to the corresponding view controller
    switch(indexPath.row){
    case 0:
        let launchScreenNC = self.storyboard?.instantiateViewController(withIdentifier: "LaunchScreenNC") as? UINavigationController
        self.navigationController?.pushViewController((self.launchScreenNC?.viewControllers.first!)!, animated: true)
        break
    case 1:
        let connectionNC = self.storyboard?.instantiateViewController(withIdentifier: "ConnectNC") as? UINavigationController
        self.navigationController?.pushViewController((self.connectionNC?.viewControllers.first!)!, animated: true)
        break
    case 2:
        let syncNC = self.storyboard?.instantiateViewController(withIdentifier: "SyncNC") as? UINavigationController
        self.navigationController?.pushViewController((self.syncNC?.viewControllers.first!)!, animated: true)
        break
    default:
        // nothing to do
        break
    }
}

It works fine for switching the first time to a new view controller. However, once initiated I want to keep those instances alive to keep a state of variables associated with each view controller.

What is the best way to do this?

I tried with

self.navigationController?.popToViewController((self.syncNC?.viewControllers.first!)!, animated: true)

or saving them as instance variables within the menu view controller, for example. But none worked so far.

I appreciate any advice.

phoebus
  • 1,280
  • 1
  • 16
  • 36

1 Answers1

1

What is the best way to do this?

The best way is don’t. Once a view controller is popped, let it go out of existence. Preserve its state (the values of its instance properties) and use that to reconstruct the interface the next time; don’t preserve the view controller instance itself.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • How do I preserve its state? In a separate container/wrapper class? And where do I store those globally then? – phoebus Apr 03 '18 at 23:27
  • However and wherever you like. Think about your needs and plan accordingly. That's what programming is. You get to design the app's architecture. – matt Apr 03 '18 at 23:29
  • @matt when you move away from lets say the root controller on the navigation stack to another, is the initial VC deallocated automatically. Thanks. – Martin Muldoon Apr 03 '18 at 23:29
  • @MartinMuldoon Not when you _push_ on top of it, no. It's a _stack_. Dishes in a pile don't disappear when you place additional dishes on top of them. But he's talking about what happens when you _pop_. – matt Apr 03 '18 at 23:39