Matt Butler Matt Butler - 1 month ago 11
Swift Question

Changing NSUserDefaults class properties after save (Swift)

Say I have a custom object defined as such:

class Person {
firstName:String,
lastName:String,
age:Int
}


After releasing an app version, say I wanted to add a
gender:String
property. How would I do this even though the current class does not contain the gender property?

Answer

You can add it in future releases of the app.
First, update your Person class, then you can set a value versionOfLastRunand check if it's nil. In this case you check if there is already a Person saved in NSUserDefaults and if it's so you create a new instance of your class to save in NSUserDefaults, with the gender and you overwrite the previous Person object.

let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
let versionOfLastRun = UserDefaults.standard.value(forKey: "VersionOfLastRun") as? String

if versionOfLastRun == nil {
    if (UserDefaults.standard.value(forKey: "Person") as? Person) != nil {
        let newPerson = Person( //... )
        UserDefaults.standard.set(currentVersion, forKey: "Person")
    } else {
        print("First run")
    }
} else if !(versionOfLastRun! == currentVersion)  {
    print("App updated")

    // Upgrade your model

} else {
    print("Nothing changed since last run")
}

UserDefaults.standard.set(currentVersion, forKey: "VersionOfLastRun")

In next releases of the app, if you want to upgrade your data model you do this by checking the version of last run.

Hope this answers to your question.