gpt4 book ai didi

iphone - 核心数据是否保存来自不同线程的更改?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:09:27 25 4
gpt4 key购买 nike

我想在主线程上更改核心数据对象,然后保存在后台线程中。后台线程保存是否包括主线程更改?

最佳答案

您可以以多线程方式使用 Core Data,但您应该遵循 approaches recommended by Apple 之一:

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.

特别是:

Using thread confinement, you should not pass managed objects or managed object contexts between threads. To “pass” a managed object from one context another across thread boundaries, you either:

Pass its object ID (objectID) and use objectWithID: or existingObjectWithID:error: on the receiving managed object context. The corresponding managed objects must have been saved—you cannot pass the ID of a newly-inserted managed object to another context.

Execute a fetch on the receiving context. These create a local version of the managed object in the receiving context.

因此,您无法在一个线程(具有自己的上下文)中创建托管对象,然后将它们保存在另一个线程中。

因此,为了完成您想要的事情,您需要在线程之间共享托管对象上下文或持久存储协调器。在这种情况下,您应该正确使用锁定技术来防止您的商店进入不一致状态:

If you share a managed object context or a persistent store coordinator between threads, you must ensure that any method invocations are made from a thread-safe scope. For locking, you should use the NSLocking methods on managed object context and persistent store coordinator instead of implementing your own mutexes. These methods help provide contextual information to the framework about the application's intent—that is, in addition to providing a mutex, they help scope clusters of operations.

我不建议走这条路,如果你有机会修改你的应用程序的设计,这样你就不需要为你的核心数据对象进行锁定和同步。

关于iphone - 核心数据是否保存来自不同线程的更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11654484/

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