gpt4 book ai didi

ios - 核心数据 3 托管对象上下文

转载 作者:行者123 更新时间:2023-11-29 10:52:31 25 4
gpt4 key购买 nike

在我的 iOS 应用程序中,我有一个用于后台线程和主线程的托管对象上下文。问题是我获取某个实体的核心数据调用可能需要大约 3-5 秒,并且继续在主线程上会很糟糕但是当我将它放在单独的托管对象上下文的后台线程上只是为了检索数据时仅用于在后台检索数据的后台线程我遇到了死锁。

我的问题是:有没有一种方法可以在后台线程中使用多个托管对象上下文?我现在正在做的事情是否应该起作用,而我只是在某个地方做错了,比如在上下文之间传递对象(我已经检查过我没有看到任何东西)?

最佳答案

托管对象上下文不是线程安全的,因此如果您需要对 Coredata 对象执行任何类型的后台工作(即长时间运行的导入/导出功能而不阻塞主 UI),您将希望在后台执行此操作线程。

在这些情况下,您需要在后台线程上创建一个新的托管对象上下文,遍历您的核心数据操作,然后将您的更改通知主上下文。

See Example Here

苹果文档:

Use Thread Confinement to Support Concurrency

The pattern recommended for concurrent programming with Core Data is thread confinement: each thread must have its own entirely private managed object context.

There are two possible ways to adopt the pattern:

Create a separate managed object context for each thread and share a single persistent store coordinator. This is the typically-recommended approach.

Create a separate managed object context and persistent store coordinator for each thread. This approach provides for greater concurrency at the expense of greater complexity (particularly if you need to communicate changes between different contexts) and increased memory usage.

关于ios - 核心数据 3 托管对象上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19870602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com