[英]How to save multiple entries in CoreData?
我有以下代码可以正确执行。 问题是它只保存最后一个条目(“Jack Daniels”,3)。 如何更改它以保存所有三个条目?
let employees = NSEntityDescription.insertNewObjectForEntityForName("Employees", inManagedObjectContext: managedObject)
employees.setValue("John Doe", forKey: "employeename")
employees.setValue(1, forKey: "id")
employees.setValue("Jane Doe", forKey: "employeename")
employees.setValue(2, forKey: "id")
employees.setValue("Jack Daniels", forKey: "employeename")
employees.setValue(3, forKey: "id")
do {
try managedObject.save()
} catch {
print("problem saving")
}
斯威夫特 4.1。 您不需要将保存代码放入 for 循环中。 只需插入所有输入,然后一次性保存它们。
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Employees", in: context)
let employeeNames = ["John Doe", "Jane Doe", "Jack Daniels"]
for (index, employee) in employeeNames.enumerated() {
let newUser = NSManagedObject(entity: entity!, insertInto: context)
newUser.setValue(employee, forKey: "employeename")
newUser.setValue(index, forKey: "id")
}
do {
try context.save()
} catch {
print("Failed saving")
}
// Alternative You can create your Entity class as below and insert entries.
import CoreData
class Employees: NSManagedObject {
@NSManaged var employeename: String
@NSManaged var id: String
func addNameAndId(name: String = "", id: String = "") throws {
if name.count > 0 {
self.employeename = name
self.id = id
} else {
throw NSError(domain: "", code: 100, userInfo: nil)
}
}
}
// Now time to insert data
let employeeNames = ["John Doe", "Jane Doe", "Jack Daniels"]
for name in employeeNames {
guard let emp = NSEntityDescription.insertNewObject(forEntityName: "Employees", into: context) as? Employees else {
print("Error: Failed to create a new Film object!")
return
}
do {
try emp.addNameAndId(name: name, id: "0")
} catch {
print("Error: \(error)\nThe quake object will be deleted.")
context.delete(emp)
}
}
// Save all the changes just made and reset the taskContext to free the cache.
if context.hasChanges {
do {
try context.save()
} catch {
print("Error: \(error)\nCould not save Core Data context.")
}
context.reset() // Reset the context to clean up the cache and low the memory footprint.
}
let employees = NSEntityDescription.insertNewObjectForEntityForName("Employees", inManagedObjectContext: managedObject)
let employees1 = NSEntityDescription.insertNewObjectForEntityForName("Employees", inManagedObjectContext: managedObject)
let employees2 = NSEntityDescription.insertNewObjectForEntityForName("Employees", inManagedObjectContext: managedObject)
employees.setValue("John Doe", forKey: "employeename")
employees.setValue(1, forKey: "id")
employees1.setValue("Jane Doe", forKey: "employeename")
employees1.setValue(2, forKey: "id")
employees2.setValue("Jack Daniels", forKey: "employeename")
employees2.setValue(3, forKey: "id")
do {
try managedObject.save()
} catch {
print("problem saving")
}
一种更紧凑(且可扩展)的方法是将您的名称数据加载到一个数组中,然后逐步执行。 您真的不想为任意长度的数组硬编码 variable1、variable2
let employeeNames = ["John Doe", "Jane Doe", "Jack Daniels"]
for (index, employee) in employeeNames.enumerate()
{
let employeeEntry = NSEntityDescription.insertNewObjectForEntityForName("Employees", inManagedObjectContext: managedObject)
employeeEntry.setValue("John Doe", forKey: "employeename")
employees.setValue(index, forKey: "id")
do {
try managedObject.save()
} catch {
print("problem saving")
}
}
这可能是基本的,但是像我这样的人可以从中受益,这就是发布我的答案的原因。 我从Gurjinder Singh发布的答案中发现,如果你想一次性保存多个元素,请插入一个唯一的 id,它也唯一地表示数据库中的每个值,否则它会添加元素,但所有元素都将被单个元素替换。 例如见下图:
guard let appDelegegate = UIApplication.shared.delegate as? AppDelegate else{
return
}
let managedContext = appDelegegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Employees", in: managedContext)!
let employeeNames = ["John Doe", "Jane Doe", "Jack Daniels"]
for index in 0..<employeeNames.count{
let newEmployee = NSManagedObject(entity: entity, insertInto: managedContext)
newEmployee.setValue(self. employeeNames[index], forKey: "employeename")
}
在这种情况下,数据库中将有三个条目,并且都是相同的。 因此,请在每个条目中插入一些唯一的 id,以将每个元素与其他元素区分开来。
for index in 0..<employeeNames.count {
let newEmployee = NSManagedObject(entity: entity!, insertInto: context)
newEmployee.setValue(employeeNames[index], forKey: "employeename")
newEmployee.setValue(index, forKey: "id")
}
是的,不要忘记在实体中添加相同的属性;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.