我需要将我的数组保存到Core Data。
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?
答案 0 :(得分:133)
好的,我做了一些研究和测试。使用 Transformable 类型,解决方案很简单:
<强> 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属性(并在访问时对其进行适当的反序列化)“ - Source
或者如果您想将其声明为二进制数据,请阅读此simple article:
答案 1 :(得分:59)
Swift 3
由于我们从Swift 3开始就没有实现文件,我们要做的是转到xcdatamodeld文件,选择实体和所需的属性(在本例中,它被称为值)。
将其设置为可转换,将其自定义类设置为[Double]
。现在将它用作普通数组。
答案 2 :(得分:11)
将数组转换为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)")
}
答案 3 :(得分:2)
如果保持简单并将数组存储为字符串
试试这个:
ErrorCode
分别对于其他数据类型:
// 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!)
答案 4 :(得分:1)
将实体属性类型设置为“二进制数据”
NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:TheArray];
myEntity.arrayProperty = arrayData;
[self saveContext]; //Self if we are in the model class
将原始数组检索为:
NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:anEntity.arrayProperty];
仅此而已。
答案 5 :(得分:0)
以下代码对我有用,可将JSON数组存储在CoreData中
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")
}
}