3

I have a program in which the user will enter data in one view controller and the information is calculated in another. I've gotten to the point where I can enter the data and when I segue to the SecondViewController I can access my data. But when I switch back to the first ViewController, the UITextFields are blank because the ViewController is re-instantiated.

Basically my application so far has one ViewController with two UITextfields and a SecondViewController that shows the data. I need a way to save the instance of the first ViewController when I am switching between the two.

I've tried using the answer from iOS Swift, returning to the same instance of a view controller , but yourVariable cannot be set to nil, so I got stuck there.

This is my code for segue-ing 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 press to go back to the first ViewController.

Community
  • 1
  • 1
K-Poch
  • 33
  • 5
  • Can you post you button code to transition back to the previous view controller? Also, you said you tried the code in that other example, did you make sure to set the identifier of the second view controller? – jzarob Jun 25 '15 at 20:34

1 Answers1

1

You can create a class to store your text file, create instance of it in appdelegate(in a global scope) and get your text data to the textfield using observer. global instance of a class may not be the best choice if your app is not as simple as you described it in which case you can use NSUsersDefault to save it as plist. I 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 = 
}
Lukas
  • 3,423
  • 2
  • 14
  • 26