如何在CoreData中保存多个条目?

时间:2016-03-23 04:20:49

标签: ios swift core-data

我有以下代码执行而没有错误。问题是它只保存最后一个条目(" Jack Daniels",3)。如何更改它以保存所有三个条目?

<h1>Screenshots</h1>
<div id = "thumbnails" align = "center"><p>hi</p></div>
<div class="gallery" align="center">
    <img name="preview" id="preview" alt=""></img>

</div>

<script type="text/javascript">
var xhttp = new XMLHttpRequest();
var output;
function update(){
    xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                console.log("readystate = 4");
                output = xhttp.responseText;
                console.log(output);
                document.getElementById("thumbnails").innerHTML = output;
            }
    }
}
function sendInfo(){
    xhttp.open("GET","http://quantumquantonium.ddns.net/images_and_videos/screenshots/php.php" ,true);
    xhttp.send();
    update();
}

sendInfo();
</script>

4 个答案:

答案 0 :(得分:3)

Swift 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.
           }

答案 1 :(得分:2)

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

答案 2 :(得分:1)

更简洁的方法(并且可扩展)可以将您的名称数据加载到数组中,然后逐步完成。你真的不想为任意长度的数组

硬编码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")
        }
    }

答案 3 :(得分:1)

这可能很基本,但是像我这样的人可能会从中受益,这就是发布我的答案的原因。我从 Gurjinder Singh 发布的答案中发现,如果您想一次保存多个元素,请插入一个唯一的ID,该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")
    }

是的,别忘了在实体中添加相同的属性;)