UserDefaults not working when switching classes (Swift 4)

My code right now takes new entries into its array. When the user hits the home button on the simulator and returns to the original view controller it works perfectly. However when the view controller is sugued to another vc and returns to the original vc and enters a new entry all of the prior entries are deleted and saved over. Basically the problem is when the user switches classes the and returns the userDefault is overwritten by a new userdefault.

                     import UIKit
    class ViewController: UIViewController {
   var persons:[Person] = [Person]()
 @IBOutlet var txt: UITextField!
@IBOutlet var label: UILabel!
@IBAction func add(_ sender: Any) {
    let judo = Person.init(name: txt.text! )
self.persons.append(judo)
label.text = String(describing: persons)
UserDefaults.standard.set(label.text, forKey: "name")
      }
           override func viewDidLoad() {
    if let name = UserDefaults.standard.value(forKey: "name") as? String {
        label.text = name
    }}
struct Person :  CustomStringConvertible  {
    var name: String
    static var myStruct = [String]();
    var description: String {
        return   "\(name)"
    }}
    }

When you write to UserDefaults the changes aren’t saved until you call synchronize()

So try this:

UserDefaults.standard.set(label.text, forKey: "name")
UserDefaults.standard.synchronize()

No, if you look at the documentation for synchronize, you see that you rarely have to call it manually. @timswift, I’m not sure from your code snippet what is happening, but you can set breakpoints on all the places that call set on UserDefaults and see if the order is what you expect.

@jarbeers I stand corrected. ‘this method is unnecessary’ - I guess maybe it was once, I’ve been calling it for years!

This topic was automatically closed after 166 days. New replies are no longer allowed.