-1

I have a strange problem with UserDefaults: Sometimes it can save and load but sometimes it doesn't work.

class ViewController: UIViewController {

    @IBOutlet var text: UITextField!
    var savedArray : [String] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        savedArray = UserDefaults.standard.object(forKey: "arr") as? [String] ?? [String]()
        print (savedArray)
    }


    @IBAction func btn(_ sender: Any) {
        savedArray.append(text.text!)
        UserDefaults.standard.set(savedArray, forKey: "arr")
    }
    
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Coco jombo
  • 51
  • 1
  • 6
  • I believe it might not work sometimes on your simulator, if you close the app fast. That's because on a simulator the default methods of iOS (for saving the state) aren't called the same way. On a device it will be fine. – Vitalii Shvetsov Sep 13 '20 at 16:52

1 Answers1

-1

Try to call UserDefaults.standard.synchronize() after set. Apple does not recommend this, but sometimes it is necessary.

Roman Ryzhiy
  • 1,540
  • 8
  • 5