CoreData 保存字典的时间太长

CoreData takes too long to save a Dictionary

提问人:bruno 提问时间:11/10/2023 最后编辑:Dávid Pásztorbruno 更新时间:11/10/2023 访问量:38

问:

我正在保存一本包含 1000 个项目的字典,大约需要 3/4 秒才能完成。在我看来,这似乎是很长一段时间。当我调用 时,这成功发生。有没有办法让它更快?addEmojisDictionary

class CoreDataManager: ObservableObject {
    
    static let shared = CoreDataManager()
    
    let container: NSPersistentContainer
    @Published var emojisEntities: [EmojiEntity] = []
    
    init() {
        container = NSPersistentContainer(name: "DataModel")
        container.loadPersistentStores { description, error in
            if let error = error {
                print("ERROR LOADING CORE DATA. \(error)")
            }
        }
    }

    func addEmojisDictionary(_ emojisDictionary: [String: String]) {
        print("addEmojis - start")
        emojisDictionary.values.forEach { value in
            let newEmoji = EmojiEntity(context: self.container.viewContext)
            newEmoji.urlString = value
            self.saveData()
        }
        print("addEmojis - end")
    }
    
    private func saveData() {
        do {
            if container.viewContext.hasChanges {
                try container.viewContext.save()
            }
        } catch {
            print("Error saving: \(error)")
        }
    }
    
}
Swift 核心数据

评论

0赞 Joakim Danielson 11/10/2023
您不需要在每次插入后调用 save(),在最后或每隔 100 次插入后调用 save()
0赞 bruno 11/10/2023
@JoakimDanielson它奏效了。谢谢!

答:

1赞 MartinM 11/10/2023 #1

除了在 forEach 循环之外只保存一次可能已经大大提高了性能,还有一点需要记住:viewContext 正在主线程上写入。对于许多用例来说,这可能不是问题,但根据从中导入数据的对象的大小,这仍然会导致 UI 断断续续。

因此,为了最佳实践,我建议您使用:

  1. 执行保存并将更改合并回 viewContext 的后台上下文。
  2. NSBatchInsertRequest(查看 Apple 的文档:https://developer.apple.com/documentation/coredata/nsbatchinsertrequest)