How to save Array to CoreData? How to save Array to CoreData? arrays arrays

How to save Array to CoreData?


Ok, I made some research and testing. Using Transformable type, solution is simple:

1. What do I declare inside my NSManagedObject class?

@NSManaged var values: [NSNumber]  //[Double] also works

2. What do I declare inside my .xcdatamodel?

Transformable data type.

3. How do I save this in my Entity?

statistics!.values = [23, 45, 567.8, 123, 0, 0] //just this

“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)” - Source

Or If you want to declare it as Binary Data then read this simple article:


Swift 3As we don't have the implementation files anymore as of Swift 3, what we have to do is going to the xcdatamodeld file, select the entity and the desired attribute (in this example it is called values). Set it as transformable and its custom class to [Double]. Now use it as a normal array.

Setting custom class to array of Double


Convert Array to NSData

let appDelegate =    UIApplication.sharedApplication().delegate as! AppDelegatelet managedContext = appDelegate.managedObjectContextlet entity =  NSEntityDescription.entityForName("Device",                                                inManagedObjectContext:managedContext)let device = NSManagedObject(entity: entity!,                             insertIntoManagedObjectContext: managedContext)let data = NSKeyedArchiver.archivedDataWithRootObject(Array)device.setValue(data, forKey: "dataOfArray")do {    try managedContext.save()    devices.append(device)} catch let error as NSError  {    print("Could not save \(error), \(error.userInfo)")}

Select Binary Data

Convert NSData to Array

let appDelegate =    UIApplication.sharedApplication().delegate as! AppDelegatelet managedContext = appDelegate.managedObjectContextlet fetchRequest = NSFetchRequest(entityName: "Device")do {    let results =        try managedContext.executeFetchRequest(fetchRequest)    if results.count != 0 {        for result in results {                let data = result.valueForKey("dataOfArray") as! NSData                let unarchiveObject = NSKeyedUnarchiver.unarchiveObjectWithData(data)                let arrayObject = unarchiveObject as AnyObject! as! [[String: String]]                Array = arrayObject        }    }} catch let error as NSError {    print("Could not fetch \(error), \(error.userInfo)")}

For Example : https://github.com/kkvinokk/Event-Tracker