Userdefaults value not saved despite syncing?

I am using UserDefaults to keep a small value that sometimes needs to be written down. I believe it is configured correctly, but I'm not sure why it doesn't work after I quit the simulator and run it again. Setting:

let defaults = UserDefaults.standard

      

It is then written to / modified like this:

defaults.set(true, forKey: "defaultsChecker")
defaults.synchronize()

      

Using the print statement, I can see that the value does update from nil to true. However, checking the value at viewDidLoad

the start of turning on the simulator again (after exiting) as follows:

print("The value is is \((defaults.value(forKey: "defaultsChecker") as! Bool)))")

      

This always returns zero at the beginning, which means it cannot be saved / saved after closing and reopening the simulator. I don’t know why this is so.

+3


source to share


1 answer


don't use value(forKey:)

to read Bool value from UserDefaults

when you set bool, usebool(forKey:)

let defaults = UserDefaults.standard
defaults.set(true, forKey: "defaultsChecker")
print("The value is is \(defaults.bool(forKey: "defaultsChecker"))")

      

here shows several types of values ​​in UserDefaults

enter image description here

and you want to get the values. Then try



defaults.integer(forKey: )
defaults.string(forKey: )
defaults.double(forKey: )
defaults.array(forKey: )
defaults.dictionary(forKey: )
defaults.data(forKey: )
defaults.bool(forKey:)

      

and no need to use synchronize()

, they sync automatically.

in your question try this ...

if let defaultsChecker =  UserDefaults.standard.object(forKey: "defaultsChecker") as? Bool {
        if defaultsChecker {
            debugPrint(defaultsChecker)// value has True
        } else  {
            debugPrint(false)// value has False
        }
    }

      

+2


source







All Articles