I am utilizing UserDefaults to save a small value that occasionally needs to be written to. I believe I have it set up correctly, but I am not sure why it is not working after I quit the simulator and start it back up again. The set up:
let defaults = UserDefaults.standard
It is then written to/modified as follows:
defaults.set(true, forKey: "defaultsChecker")
defaults.synchronize()
Using a print statement I can see that the value is indeed updated from being nil to being true. However, checking the value in a viewDidLoad
at the onset of turning the simulator on again (after being quit) as follows:
print("The value is is \((defaults.value(forKey: "defaultsChecker") as! Bool)))")
This always returns nil at the onset, meaning that it must not be saved/persist through the closing and reopening of the simulator. Not sure why this is the case.
don't use value(forKey:)
for read Bool Value from UserDefaults
you when you set bool then use bool(forKey:)
let defaults = UserDefaults.standard
defaults.set(true, forKey: "defaultsChecker")
print("The value is is \(defaults.bool(forKey: "defaultsChecker"))")
here shown multiple types of value in UserDefaults
and you want to get values,Then try this
defaults.integer(forKey: )
defaults.string(forKey: )
defaults.double(forKey: )
defaults.array(forKey: )
defaults.dictionary(forKey: )
defaults.data(forKey: )
defaults.bool(forKey:)
and there is no need to use synchronize()
they automatically sync .
in your question you 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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With