Swift 3多核心数据保存

时间:2017-02-14 17:51:01

标签: arrays swift core-data

我需要像对象一样保存每个字符串,但在下面的方法中只保存最后一个字符串。

请告诉我如何保存所有内容?

          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
                    {

                    }
                }

1 个答案:

答案 0 :(得分:0)

如果要在每次迭代中创建新的托管对象,请将let newInfo移动到循环中

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

此外,强烈建议您在 循环后保存上下文。