ios 如何将数组保存到 CoreData?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29825604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save Array to CoreData?
提问by Bart?omiej Semańczyk
I need to save my array to Core Data.
我需要将我的数组保存到 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?
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. What do I declare inside my .xcdatamodel?
2. 我在我的 .xcdatamodel 中声明了什么?
3. How do I save this in my Entity?(I use MagicalRecord)
3. 如何将其保存在我的实体中?(我使用 MagicalRecord)
let statistics = (PBOStatistics.MR_createInContext(context) as! PBOStatistics)
statistics.values = [8, 17.7, 18, 21, 0, 0, 34] //is it enough?
回答by Bart?omiej Semańczyk
Ok, I made some research and testing. Using Transformabletype, solution is simple:
好的,我做了一些研究和测试。使用Transformable类型,解决方案很简单:
1. What do I declare inside my NSManagedObject class?
1. 我在 NSManagedObject 类中声明了什么?
@NSManaged var values: [NSNumber] //[Double] also works
2. What do I declare inside my .xcdatamodel?
2. 我在我的 .xcdatamodel 中声明了什么?
Transformable
data type.
Transformable
数据类型。
3. How do I save this in my Entity?
3. 如何将其保存在我的实体中?
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
“您可以将 NSArray 或 NSDictionary 存储为可转换属性。这将使用 NSCoding 将数组或字典序列化为 NSData 属性(并在访问时对其进行适当的反序列化)”-来源
Or If you want to declare it as Binary Datathen read this simple article:
或者,如果您想将其声明为二进制数据,请阅读这篇简单的文章:
回答by Hola Soy Edu Feliz Navidad
Swift 3As we don't have the implementation files anymore as of Swift 3, what we have to do is going to the xcdatamodeld file, select the entity and the desired attribute (in this example it is called values).
Set it as transformable and its custom class to [Double]
. Now use it as a normal array.
Swift 3由于从Swift 3 开始我们不再有实现文件,我们要做的是转到 xcdatamodeld 文件,选择实体和所需的属性(在本例中称为值)。将其设置为可转换并将其自定义类设置为[Double]
. 现在将其用作普通数组。
回答by Vinoth Anandan
Convert Array to 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)")
}
Convert NSData to Array
将 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)")
}
For Example : https://github.com/kkvinokk/Event-Tracker
回答by Alexey Chekanov
If keeping it simple and store an array as a string
如果保持简单并将数组存储为字符串
Try this:
尝试这个:
// 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!)
For other data types respectively:
分别对于其他数据类型:
// 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!)
回答by Avijit Nagare
Make entity attribute type as "Binary Data"
将实体属性类型设为“二进制数据”
NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:TheArray];
myEntity.arrayProperty = arrayData;
[self saveContext]; //Self if we are in the model class
Retrive original array as:
将原始数组检索为:
NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:anEntity.arrayProperty];
That's all.
就这样。
回答by Rahul Gusain
Following code works for me to store array of JSON in CoreData
以下代码适用于我在 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")
}
}