Saving the ViewController Instance

I have a program where a user enters data into one view controller and the information is calculated in another. I got to the point where I can enter data, and when I go to the SecondViewController, I can access my data. But when I switch back to the first ViewController the UITextFields are empty because the ViewController is re-instantiated.

Basically my application still has one ViewController with two UIText fields and a SecondViewController that shows the data. I need a way to keep an instance of the first ViewController when I switch between them.

I tried to use the answer from iOS Swift back to the same view controller instance , but yourVariable cannot be set to zero, so I am stuck there.

This is my code for going from the first ViewController to the SecondViewController

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) 
  {
  if (segue.identifier == "Show")
     {
      var destinationVC = segue.destinationViewController as! MainViewController
     }
  }

      

I only have a button that I click to return to the first ViewController.

+3


source to share


1 answer


You can create a class to store a text file, instantiate it in the appdelegate (in the global scope), and get the text data into the text field using an observer. a global class instance may not be the best choice if your application is not as simple as you described it, in which case you can use NSUsersDefault to save it as a plist. Hope I helped :)



//in first view controller
@IBOutlet weak var textfield: UITextField!{
    didSet{
        textfield.text = text
    }
}
var text:String = ""{
    didSet{
        textfield?.text = text
    }
}
func override viewWillAppear(animated: Bool) {
    //set value of text from your global class instance or
    //decode it here from the archive file if you used NSUsersDefault 
    text = 
}

      

+1


source







All Articles