如何将 Array 保存为 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 中声明什么?

enter image description here

3. 如何在我的实体中保存它? (我使用 MagicalRecord)

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

好的,我做了一些研究和测试。使用 变形金刚型,解决方案很简单:

1. 在 NSManagedObject 类中声明什么?

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

2. 在.xcdatamodel 中声明什么?

Transformable数据类型。

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)")
}

Select Binary Data

将 NSData 转换为 Array

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 文件,选择实体和所需的属性(在本例中称为 value)。 将其设置为可转换的,并将其自定义类设置为 [Double]。现在将其作为普通数组使用。

Setting custom class to array of Double

如果保持简单,并将数组存储为字符串

试试这个:

// Array of Strings
let array: [String] = ["red", "green", "blue"]
let arrayAsString: String = array.description
let stringAsData = arrayAsString.data(using: String.Encoding.utf16)
let arrayBack: [String] = try! JSONDecoder().decode([String].self, from: stringAsData!)

其他数据类型:

// Set of Doubles
let set: Set<Double> = [1, 2.0, 3]
let setAsString: String = set.description
let setStringAsData = setAsString.data(using: String.Encoding.utf16)
let setBack: Set<Double> = try! JSONDecoder().decode(Set<Double>.self, from: setStringAsData!)

将实体属性类型设置为“二进制数据”

NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:TheArray];
myEntity.arrayProperty = arrayData;
[self saveContext]; //Self if we are in the model class

返回原始数组:

NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:anEntity.arrayProperty];

仅此而已。

下面的代码用于在 CoreData 中存储 JSON 数组

func saveLocation(model: [HomeModel],id: String){


let newUser = NSEntityDescription.insertNewObject(forEntityName: "HomeLocationModel", into: context)


do{
var dictArray = [[String: Any]]()
for i in 0..<model.count{
let dict = model[i].dictionaryRepresentation()
dictArray.append(dict)
}
let data = NSKeyedArchiver.archivedData(withRootObject: dictArray)
newUser.setValue(data, forKey: "locations")
newUser.setValue(id, forKey: "id")
try context.save()
}catch {
print("failure")
}


}