0

I have this app with a TextField and a Save Button that I want to save when I close after it has been edited and load when I open but I cannot figure it out.
I have written something but when I try to start there comes always the

error: "Fatal 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

This is the code (that is in the my ViewController) but I don't know if its the best way to do it:

@IBOutlet weak var numText: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        if UserDefaults.standard.object(forKey: "num") == nil {
            numText.text = "15"
        }
        else {
            let number = UserDefaults.standard.object(forKey: "num") as! String
            numText.text =  number
        }
        // Do any additional setup after loading the view, typically from a nib.
    }
    @IBAction func saveButtonPressed(_ sender: UIButton) {
        if numText.text == nil {
            UserDefaults.standard.set("15", forKey: "num")
        }
        else {
            UserDefaults.standard.set(numText.text, forKey: "num")
        }


    }
iGatiTech
  • 2,306
  • 1
  • 21
  • 45
J.Demand
  • 15
  • 4
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Cristik Mar 05 '18 at 09:11
  • I think your numText IBOutlet is not connected with textfield – aBilal17 Mar 07 '18 at 12:46
  • No, its definitely connected. – J.Demand Mar 07 '18 at 13:28

1 Answers1

0

Add the text as a computed Property in the ViewController:

var SAVEDTEXTKEY = "num"
var savedText: String? {
    set{
        guard let value = newValue else {
            UserDefaults.standard.removeObject(forKey: SAVEDTEXTKEY)
            UserDefaults.standard.synchronize()
            return
        }
        UserDefaults.standard.set(value, forKey: SAVEDTEXTKEY)
        UserDefaults.standard.synchronize()
    }
    get{
        return UserDefaults.standard.string(forKey: SAVEDTEXTKEY)
    }
}

After that, when you want to save just do :

self.savedText = self.numText?.text

And when you want to retrieve it just do:

self.numText.text = self.savedText

The problem I think is that you're not calling

UserDefaults.standard.synchronize()

after setting the value in user defaults.

Agent Smith
  • 2,873
  • 17
  • 32