I am using the method suggested in
Saving custom Swift class with NSCoding to UserDefaults
to store a custom class object. But it appears that the property values were not saved - perhaps due to the class initialization overriding the stored value? Or the updated value were never saved?
class Test : Codable {
var testedValues: float
init () {
testedValues = 0.0
}
}
var myTest = Test()
// retrieve
if let testData = UserDefaults.standard.data(forKey: "myTest"),
let myTest = try? JSONDecoder().decode(Test.self, from: testData) {
}
//testValues is 0.0 each time the app starts up
print (myTest.testValues)
myTest.testValues += 1.0
//save in UserDefaults
if let encoded = try? JSONEncoder().encode(myTest) {
UserDefaults.standard.set(encoded, forKey: "myTest")
}