将数据插入核心数据模型的速度太慢了

时间:2019-03-12 03:03:11

标签: swift core-data

我需要能够每周导入超过100,000条记录。数据来自Web服务,为CSV文件。下载速度很快,就像将其按摩成可用形式一样。但是,将记录添加到模型中是可行的,但是速度却慢得令人无法接受-几乎一个小时!

我知道我在保存每条记录后都在保存。必须有更好的方法来做到这一点。

请提出建议或指向我其他答案。这是我的工作代码。非常感谢。

func loadDataBase() {

    for i in 1..<objectArray.count - 1 {

        let item: [String] = objectArray[i]


        s_stop_id = Int(item[0])
        s_stop_code = Int(item[1])
        s_stop_name = item[2]

        let mainDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = mainDelegate.persistentContainer.viewContext

        let newResource = NSEntityDescription.insertNewObject(forEntityName: stopEntity, into: context)

        newResource.setValue(s_stop_id, forKey: "stop_id")
        newResource.setValue(s_stop_name, forKey: "stop_name")
        newResource.setValue(s_stop_code, forKey: "stop_code")


        do {
            try context.save()

        } catch let error as NSError  {
            print("Error While Saving Data: \(error.userInfo)")
        }
    }

我正在显示一些使用情况信息。我似乎正在使用100%CPU。在后台运行此过程是否可行?那么时间安排就不是问题了。

enter image description here

2 个答案:

答案 0 :(得分:2)

您可能应该实例化上下文并将其保存在for之外,就像这样:

func loadDataBase() {

    let mainDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = mainDelegate.persistentContainer.viewContext

    for i in 1..<objectArray.count - 1 {

        let item: [String] = objectArray[i]


        s_stop_id = Int(item[0])
        s_stop_code = Int(item[1])
        s_stop_name = item[2]



        let newResource = NSEntityDescription.insertNewObject(forEntityName: stopEntity, into: context)

        newResource.setValue(s_stop_id, forKey: "stop_id")
        newResource.setValue(s_stop_name, forKey: "stop_name")
        newResource.setValue(s_stop_code, forKey: "stop_code")
    }
    do {
            try context.save()

        } catch let error as NSError  {
            print("Error While Saving Data: \(error.userInfo)")
        }
}

答案 1 :(得分:2)

使用autoreleasepool测试以下内容。

let mainDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let newResource = NSEntityDescription.insertNewObject(forEntityName: stopEntity, into: context)

for i in 1..<objectArray.count - 1 {
    autoreleasepool(invoking: { () -> () in
        let item: [String] = self.objectArray[i]
        s_stop_id = Int(item[0])
        s_stop_code = Int(item[1])
        s_stop_name = item[2]
        newResource.setValue(s_stop_id, forKey: "stop_id")
        newResource.setValue(s_stop_name, forKey: "stop_name")
        newResource.setValue(s_stop_code, forKey: "stop_code")

        do {
            try context.save()
        } catch let error as NSError  {
            print("Error While Saving Data: \(error.userInfo)")
        }    
    })
}