Saving an array of objects in UserDefaults

1.9k Views Asked by At

Using swift 3.0, I'm trying to add an array of objects into user defaults. As this isn't one of the regular UserDefault types I've realised that the object or array of objects (can't work out which one) will need to be parsed to the type NSData to then be added to UserDefaults.

My attempt so far is the following:

Within the object

func updateDefaults()
{
    let data = NSData(data: MyVariables.arrayList)
    UserDefaults.standard.set(data, forKey: "ArrayList")
}

Where MyVariables.arrayList is the array of objects.

Lastly, if possible it would be nice to know how to retrieve this from UserDefaults and convert it to the original one-dimensional array of objects.

Thanks

REPOSITORY: https://github.com/Clisbo/ModularProject

1

There are 1 best solutions below

0
Arashk On

You can't save your custom array in NSUserDefaults. To do that you should change them to NSData then save it in NSUserDefaults Here is the code.

var custemArray: [yourArrayType] {
    get {
        if let data = NSUserDefaults.standardUserDefaults().objectForKey("yourKey") as? NSData {
           let myItem = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? yourType
        }
    }
    set {
        let data =NSKeyedArchiver.archivedDataWithRootObject(yourObject);
        NSUserDefaults.standardUserDefaults().setObject(data, forKey: "yourKey")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
}