首页 > 解决方案 > 将数据插入核心数据模型的速度慢得令人无法接受

问题描述

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

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

请建议或指出我另一个答案。这是我的工作代码。非常感谢。

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。在后台运行这个过程是否可行?那么时间就不是什么大问题了。。

在此处输入图像描述

标签: swiftcore-data

解决方案


用 测试以下内容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)")
        }    
    })
}

推荐阅读