I'm doing save a list of data into core data by using the for each loop here. However, it only helping me to save the last data in the for loop into core data, what problem is it? I couldn't manage to save all the data into core data. Below is my code that I'm working on it...
let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context : NSManagedObjectContext = appDelegate.managedObjectContext
let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext:context)
RestApiManager.sharedInstance.makeGetRequest("testingserver", onCompletion: {json in
for result in json["record"].arrayValue
{
print(result)
let id = result["mc_termid"].stringValue
let name = result["mc_name"].stringValue
let parent = result["mc_parent"].stringValue
let color = result["mc_color"].stringValue
let update = result["mc_updated"].stringValue
let termName = result["mc_termname"].stringValue
let status = result["mc_status"].stringValue
category.setValue(id, forKey: "mc_termid")
category.setValue(name, forKey: "mc_name")
category.setValue(parent, forKey: "mc_parent")
category.setValue(color, forKey: "mc_color")
category.setValue(update, forKey: "mc_updated")
category.setValue(termName, forKey: "mc_termname")
category.setValue(status, forKey: "mc_status")
}
do
{
try context.save()
print("Category save to local database successfully.")
}
catch
{
}
})
You need to insert an managedobject every time you iterate one element in the array.
So put the category declaration into the iterating block.
let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context : NSManagedObjectContext = appDelegate.managedObjectContext
RestApiManager.sharedInstance.makeGetRequest("testingserver", onCompletion: {json in
for result in json["record"].arrayValue
{
let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext:context)
print(result)
let id = result["mc_termid"].stringValue
let name = result["mc_name"].stringValue
let parent = result["mc_parent"].stringValue
let color = result["mc_color"].stringValue
let update = result["mc_updated"].stringValue
let termName = result["mc_termname"].stringValue
let status = result["mc_status"].stringValue
category.setValue(id, forKey: "mc_termid")
category.setValue(name, forKey: "mc_name")
category.setValue(parent, forKey: "mc_parent")
category.setValue(color, forKey: "mc_color")
category.setValue(update, forKey: "mc_updated")
category.setValue(termName, forKey: "mc_termname")
category.setValue(status, forKey: "mc_status")
}
do
{
try context.save()
print("Category save to local database successfully.")
}
catch
{
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.