2017-02-14 116 views
-1

我需要將每個字符串保存爲一個對象,但在以下方法中只保存最後一個字符串。Swift 3多核心數據保存

你能告訴我如何保存一切嗎?

  let appDelegate = UIApplication.shared.delegate as! AppDelegate 

      let context = appDelegate.persistentContainer.viewContext 
      if let doc = HTML(html: sentHTML, encoding: .utf8) { 
       print(doc.title!) 
       var kCounter = 2 
       var Variab = false 
       let newInfo = NSEntityDescription.insertNewObject(forEntityName: "MarksTable", into: context) 
       for link in doc.xpath("//td | //link") { 

        if (kCounter % 2) == 0 { 

         newInfo.setValue(link.text!, forKey: "lesson") 
        } 
        if (kCounter % 2) == 1 { 

         newInfo.setValue(link.text!, forKey: "mark") 
        } 
        kCounter += 1 

        do 
        { 
         try context.save() 
         print("saved ",link.text!) 

        } 
        catch 
        { 

        } 
       } 

回答

0

如果你想在每次迭代中創建一個新的管理對象,移動let newInfo進入循環

for link in doc.xpath("//td | //link") { 
    let newInfo = NSEntityDescription.insertNewObject(forEntityName: "MarksTable", into: context) 
    ... 

而且我們強烈建議保存上下文一次循環。