如何将数组保存到CoreData?

我需要将我的数组保存到核心数据。

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

该数组内的值和值的数量是可变的。

1.我在NSManagedObject类中声明了什么?

 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.我在.xcdatamodel中声明什么?

在这里输入图像说明

3.我如何将这个保存在我的实体? (我使用MagicalRecord)

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

好吧,我做了一些研究和testing。 使用Transformabletypes,解决scheme很简单:

1.我在NSManagedObject类中声明了什么?

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

2.我在.xcdatamodel中声明什么?

Transformable数据types。

3.我如何将这个保存在我的实体?

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

“您可以将NSArray或NSDictionary存储为可转换属性。 这将使用NSCoding序列化数组或字典到一个NSData属性(并适当反序列化访问)“ – 来源

或者如果你想声明它为二进制数据然后阅读这个简单的文章 :

将数组转换为NSData

 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let 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)") } 

选择二进制数据

将NSData转换为数组

 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let 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)") } 

例如: https : //github.com/kkvinokk/Event-Tracker

Swift 3因为我们还没有Swift 3的实现文件,我们要做的就是去xcdatamodeld文件,select实体和所需的属性(在这个例子中,它被称为值)。 将其设置为可变形,并将其自定义类设置为[Double] 。 现在使用它作为一个正常的数组。

将自定义类设置为Double数组

Swift 2.3

 import UIKit import CoreData @objc(Merchant_Status) class Merchant_Status: NSManagedObject { @NSManaged var data: [AnyObject] @NSManaged var uniqueKey: String } // MARK: - // MARK: - MERCHANT STATUS extension CoreDataHelper{ class func saveMerchantStatus(data :[AnyObject]) { let uniqueKey = MERCHENT_INFO.MERCHANT_ID let context: NSManagedObjectContext = CoreDataHelper.managedObjectContext() let request = NSFetchRequest(entityName: "Merchant_Status") request.predicate = NSPredicate(format: "uniqueKey = %@", uniqueKey) do { let fetchedEntities = try CoreDataHelper.managedObjectContext().executeFetchRequest(request) if fetchedEntities.count != 0{ let managedObject = fetchedEntities[0]as! NSManagedObject managedObject.setValue(data, forKey: CoredataConstant.kDATA) do { try context.save() } catch { print(error) } }else{ let entityDescription = NSEntityDescription.entityForName("Merchant_Status", inManagedObjectContext:CoreDataHelper.managedObjectContext()) let context = NSManagedObject(entity: entityDescription!, insertIntoManagedObjectContext:CoreDataHelper.managedObjectContext()) context.setValue(data, forKey: CoredataConstant.kDATA) context.setValue(uniqueKey, forKey: CoredataConstant.kUNIQUE_KEY) //unique value do { try context.managedObjectContext?.save() } catch { print(error) } } } catch { print(error) } } class func getMerchantStatus() -> [String:AnyObject]{ let fetchRequest = NSFetchRequest() let entityDescription = NSEntityDescription.entityForName("Merchant_Status", inManagedObjectContext: CoreDataHelper.managedObjectContext()) fetchRequest.entity = entityDescription var parameters:[String:AnyObject] = [String: AnyObject]() do { let result = try CoreDataHelper.managedObjectContext().executeFetchRequest(fetchRequest) if (result.count > 0) { let person = result[0] as! NSManagedObject let deposits_Amount:[AnyObject] = person.valueForKey(CoredataConstant.kDATA)! as! [AnyObject] parameters = deposits_Amount[0] as! [String:AnyObject] } } catch { let fetchError = error as NSError print(fetchError) } return parameters } } 

在这里输入图像说明