将数据列表保存到核心数据iOS Swift中

时间:2016-01-08 02:04:30

标签: ios swift core-data

我在这里使用for each循环将数据列表保存到核心数据中。但是,它只能帮助我将for循环中的最后数据保存到核心数据中,它有什么问题?我无法将所有数据保存到核心数据中。以下是我正在处理的代码......

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
    {

    }
})

1 个答案:

答案 0 :(得分:1)

每次迭代数组中的一个元素时,都需要插入一个managedobject 所以将类别声明放入迭代块中。

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
    {

    }
})