beninabox_uk
beninabox_uk

Reputation: 684

Save an Array of Data in Swift in NSUserDefaults

I have an array of data that I have created in Swift in Xcode.

I have setup a structure to store my data using the following code:

struct groups {
    var groupName: String!
    var groupPeripherals: [CBPeripheral]!
}

The arrays work fine and the array is held until the app is closed.

I have then created an array using this structure as so:

var groupArray = [groups]()

Throughout the app, I have appended data to this array like this, for example:

groupArray.append(groups(groupName: "Group 1", groupPeripherals: [peripheral info...]))

Where I have written 'peripheral info', it actually passes the CBPeripheral information to the array.

Anyway, to the question. I want to be able to store this array in NSUserDefaults and be able to read it when I restart the app. How would I go about doing this? I know how to use NSUserDefaults with Strings and Integers etc, but not this kind of array. Any help would be appreciated here.

Thanks!

Upvotes: 0

Views: 693

Answers (1)

Duncan C
Duncan C

Reputation: 131501

NSUserDefaults can only save "property list objects". (see link for a list of supported data types.)

In order to save an array to user defaults, every single object in the array's "object graph" must be a property list type.

You need to convert your structures to property list types. You can implement NSCoding for your objects and then use the NSKeyedArchiver method archivedDataWithRootObject to convert your array to NSData and save that.

Alternately you could define helper methods in your struct that convert it to/from a dictionary, then use filter() to convert your array of groups structures to an array of dictionaries and save that to user defaults.

EDIT:

I see that your structure contains CBPeripheral objects. You'll need to convert those to a form that can be saved to user defaults as well. One option would be to create an extension to CBPeripheral that adds NSCoding support.

In general you want to avoid saving large amounts of data to user defaults. You might want to save your data to a file in the documents directory instead. (using the same sort of technique you'd use to write to user defaults.)

Upvotes: 2

Related Questions