kev.a kev.a - 1 month ago 6
iOS Question

Store an Array attribute in the Data Base

I have an attribute in my entity that should store multiple Int.
This is how the recieved JSON from the API looks like

{
"type": “KsCell”,
“id”: 23,
“allowedSize”: [1,2],
},


How can I declare/store this in the xcdatamodeld?

this is a list of attribute I can choose from, there is no array

enter image description here

Answer

There is no "native" array or dictionary type in Core Data. You can store an NSArray or an NSDictionary as a transformable attribute. This will use the NSCoding to serialize the array or dictionary to an NSData attribute (and appropriately deserialize it upon access). - src

So, possible solution might be using of Transformable type.

As an expample, you can declare it in your NSManagedObject as:

@NSManaged var allowedSizes: [NSNumber]

and assign your parsed ints array from json

myObject!.allowedSizes = allowedSizeArray //[1,2]

Another solution is to use NSKeyedArchiver to convert your array into NSData.

let allowedSizes = NSKeyedArchiver.archivedDataWithRootObject(allowedSizeArray) // NSData