iosarraysswiftcore-datamagicalrecord

How to save Array to CoreData?


I need to save my array to Core Data.

let array = [8, 17.7, 18, 21, 0, 0, 34]

The values inside that array, and the number of values are variable.

1. What do I declare inside my NSManagedObject class?

class PBOStatistics: NSManagedObject, Equatable {
    @NSManaged var date: NSDate
    @NSManaged var average: NSNumber
    @NSManaged var historicAverage: NSNumber
    @NSManaged var total: NSNumber
    @NSManaged var historicTotal: NSNumber
    @NSManaged var ordersCount: NSNumber
    @NSManaged var historicOrdersCount: NSNumber
    @NSManaged var values: [Double]  //is it ok?

    @NSManaged var location: PBOLocation

}

2. What do I declare inside my .xcdatamodel?

enter image description here

3. How do I save this in my Entity? (I use MagicalRecord)

let statistics = (PBOStatistics.MR_createInContext(context) as! PBOStatistics)
statistics.values = [8, 17.7, 18, 21, 0, 0, 34] //is it enough?

Solution

  • 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: