Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Userdefaults value not persisting despite being synchronized?

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.

like image 880
Runeaway3 Avatar asked Oct 18 '22 12:10

Runeaway3


1 Answers

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

enter image description here

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
        }
    }
like image 200
ItsMeMihir Avatar answered Oct 21 '22 09:10

ItsMeMihir