Reputation: 17
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
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