如何将数组保存到CoreData?

x759pob2  于 2022-10-23  发布在  Swift
关注(0)|答案(6)|浏览(268)

我需要将我的数组保存到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?
zfciruhq

zfciruhq1#

好的,我做了一些研究和测试。使用可转换类型,解决方案很简单:

1.在NSManagedObject类中声明什么?

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

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

Transformable数据类型。

3.如何将其保存在我的实体中?

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

“您可以将NS数组或NSDictionary存储为可转换属性。这将使用NSCoding将数组或字典序列化为NSData属性(并在访问时适当地反序列化它)“-Source
或者,如果您想将其声明为二进制数据,请阅读simple article

oaxa6hgo

oaxa6hgo2#

SWIFT 3由于从SWIFT 3开始我们不再有实施文件,我们要做的是转到xcdatamodeld文件,选择实体和所需的属性(在本例中称为值)。将其设置为Transformable,并将其自定义类设置为[Double]。现在将其用作普通数组。

ijnw1ujt

ijnw1ujt3#

将数组转换为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

gwbalxhn

gwbalxhn4#

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

试试这个:

// 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!)
k2arahey

k2arahey5#

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

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

将原始数组检索为:

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

就这样。

ao218c7q

ao218c7q6#

下面的代码适用于我在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")
    }

}

相关问题