简体   繁体   中英

Saving an array of objects in UserDefaults

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

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()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM