1

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

  • Maybe this will be helpful for you http://stackoverflow.com/questions/29215825/how-to-store-array-list-of-custom-objects-to-nsuserdefaults –  Dec 30 '16 at 11:19
  • did you try this? http://stackoverflow.com/questions/6696558/storing-data-to-nsuserdefaults – Museer Ahamad Ansari Dec 30 '16 at 11:19
  • Check this one http://stackoverflow.com/questions/41355427/attempt-to-insert-non-property-list-object-when-trying-to-save-a-custom-object-i – Nirav D Dec 30 '16 at 11:26
  • Museer looks helpful but I don't understand objective-C whatsoever, thanks though. Muhammad I looked for so long thanks that look helpful (don't know why it didn't come up when I searched for it...) – Matthew Clisby Dec 30 '16 at 11:26
  • I've tried some of these and nothing seems to be working, I would really appreciate it if anyone could look at my program in the link in the main description – Matthew Clisby Dec 30 '16 at 11:54
  • I don't know, how big that array is, but you should avoid storing big data structures in user defaults! (It is actually part of the documentation, I think) For bigger data structures, CoreData is certainly advisable (but hard to learn), but you might also be able to use `NSKeyedArchiver`. – borchero Dec 30 '16 at 14:27

1 Answers1

0

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()
    }
}
Arashk
  • 617
  • 5
  • 16