Dmitry Memeboy
Dmitry Memeboy

Reputation: 17

Swift 3 multiple core data saving

I need to save each string like an object, but in the following method only the last string is saving.

Can you please tell me how can i save everything?

          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
                    {

                    }
                }

Upvotes: 0

Views: 51

Answers (1)

vadian
vadian

Reputation: 285059

If you want to create a new managed object in each iteration, move let newInfo into the loop

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

Further it's highly recommended to save the context once after the loop.

Upvotes: 1

Related Questions