swift - 将数据插入核心数据模型的速度慢得令人无法接受
问题描述
我需要能够每周导入超过 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。在后台运行这个过程是否可行?那么时间就不是什么大问题了。。
解决方案
用 测试以下内容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)")
}
})
}
推荐阅读
- vscode-settings - VS 代码编辑器不像响应式网站那样响应。0
- c# - 如何使用 RestSharp c# 验证 SSL 证书
- javascript - 调整事件侦听器大小后类方法中断
- python - 有什么我做错了吗?我没有收到任何错误,但没有显示输出
- javascript - 焦点在文本区域时反应热键 cntrl+s
- spring - 为什么 Spring Cassandra 不将 @Table 中设置的值与 Scala 一起使用?
- haskell - 如何在 Options.Applicative 中为互斥标志编码
- python - 无法使用 Tensorflow.JS 转换 GPT-2 模型
- javascript - 如何在 asp.net mvc 中修复日期 /Date(xxxxxxxxxxxxxxx)/?
- go - 如何将多个证书路由到一个 Flynn 应用程序?