I want to save some values in UserDefaults
. And I am using this code to save
func SaveSettings(){
let def = UserDefaults.standard
def.set("test", forKey: "Value1")
def.set(myString, forKey: "Value2") //value: test1
def.set(myInt, forKey: "Value3") //value: 25
def.set(myInt64, forKey: "Value4") //value: 103254
def.synchronize() //I've tried to remove this line
}
After saving I use this code to control if my values are saved in UserDefaults
or not
for (key, value) in UserDefaults.standard.dictionaryRepresentation() {
print("\(key) = \(value) \n")
}
And see this result
{
Value1 = test
Value2 = test1
Value3 = 25
Value4 = 103254
}
There isn't any problem untill now. But After I restart the app and look at the values in UserDefaults
I see this result
{
Value1 = test
Value2 =
}
As you see Value3
ad Value4
are missing. However Value2
and Value1
stays. but Value2
's value is missing
I've found the problem.
SaveSettings()
func have called when myInt
and myInt64
's values are nil
and myString
's value is empty. Somehow Value3
and Value4
are deleted here. I guess this happen becaues of their value is nil
. But I am not sure this is exact reason.