1

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")
}
zero3nna
  • 2,770
  • 30
  • 28
Yan
  • 137
  • 1
  • 9
  • 1
    Never use `try?` with `JSONDecoder` or `JSONEncoder`. Use `try` in a `do/catch` and be sure to `print(error)` in the `catch` so you can see what the error is, if any. – rmaddy May 07 '19 at 06:07

1 Answers1

1

You've saved the custom class successfully with its properties. The mistake you are doing here is you are retrieving the stored value and printing the newly created instance. Don't use the same name myTest for both instances. Store the retrieved value in myTest

if let testData = UserDefaults.standard.data(forKey: "myTest"),
    let storedMyTest = try? JSONDecoder().decode(Test.self, from: testData) {
        self.myTest = storedMyTest
}

To save the testedValues in UserDefaults automatically whenever it is changed use computed variable like this

class Test: Codable {
    var testedValues: Double {
        didSet {
            //save in UserDefaults
            if let encoded = try? JSONEncoder().encode(self) {
                UserDefaults.standard.set(encoded, forKey: "myTest")
            }
        }
    }
    init () {
        testedValues = 0.0
    }
}
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70
  • It worked. Thank you! A follow-up question - as I am fairly new in iOS app - the testValues are updated in a few places, including some functions, but I am not sure if it is good idea to do the save everytime the testeValues are updated. Is there a good place (e.g. in the viewController) to place the save codes, and still guaranteed the values are saved when the user quit the App? – Yan May 07 '19 at 07:15