2

I have a problem, where I have two view controllers A and B. View controller B has a map, with a route draw on it. I can move back and forwards between the two view controllers at the moment, but the B view controller is reset every time it loads. I think this is because I am using segues and it is creating a new instance of a View controller every time.

I have tried using the following code to solve this issue, but it is still not working. The views load correctly, but view controller B is still being reset

@IBAction func mapButton(sender: AnyObject){
        let storyboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as! UIViewController
        self.presentViewController(vc, animated: true, completion: nil)
}

What am I doing wrong and how can I fix it? I want view controller B to stay in the memory along with the map and the route, so when a user returns he doesn't have to enter all of the information again.

Gux
  • 23
  • 1
  • 4

1 Answers1

4

You should create a variable in your class of type UIViewController and change your code to the following:

@IBAction func mapButton(sender: AnyObject){
    if yourVariable == nil {
        let storyboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
        yourVariable = storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as! UIViewController
    }
    self.presentViewController(yourVariable, animated: true, completion: nil)
}

That way you create the viewController one time, save it and if you want to open it again present the previously created one.

luk2302
  • 55,258
  • 23
  • 97
  • 137
  • Thanks for the help, this works now. Makes sense now, I don't know how I managed to overlook that. – Gux May 01 '15 at 19:17
  • No problem. If my answer solved your problem, please accept it by clicking the check mark below the answer count on the left. – luk2302 May 01 '15 at 19:19
  • Better yet, lazy load `yourVariable`. Then you only need to check if it's nil in one place. – AdamPro13 May 01 '15 at 19:21
  • Yes! That might make things even easier. @Gux: that would mean writing a function `getMyViewController` which checks if `yourVariable` is set already and instantiates if that was not the case. (would be the same as above) Then it just returns that variable. That way you can access your variable via calling that function and be sure that you get a valid viewController returned. Unfortunately i dont write swift code and therefore cant add the corresponding lines to my answer :/ – luk2302 May 01 '15 at 19:27