是NSPersistentStoreCoordinator线程安全吗? [英] Is NSPersistentStoreCoordinator Thread Safe?

查看:182
本文介绍了是NSPersistentStoreCoordinator线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个使用Core Data的iPhone应用程式。该应用程序调用Web服务,解析生成的XML文件,然后在我的应用程序中创建或修改Core Data对象。我已经处理了Web服务调用和异步解析,但我一直把解析的数据回到主线程来操作Core Data对象。我想在后台线程中运行这个过程。 (1-2秒暂停不会给用户带来很好的体验)

I'm working on an iPhone app that uses Core Data. The app makes a call to a web service, parses the resulting XML file, and then creates or modifies Core Data objects in my app. I already handle the web service call and parsing asynchronously, but I've been handing the parsed data back to the main thread to manipulate the Core Data objects. I'd like to run this process in the background thread as well. (A 1-2 second pause doesn't make for a great user experience)

显而易见的方法是为后台线程创建一个托管对象上下文,那么我在 Apple的核心数据编程指南

The obvious approach would be to create a managed object context specifically for the background thread, but then I read this line in Apple's Core Data Programming Guide:


持久存储协调器向其托管对象上下文提供外观的一个虚拟商店。对于完全并发操作,您需要为每个线程使用不同的协调器。

A persistent store coordinator provides to its managed object contexts the façade of one virtual store. For completely concurrent operations you need a different coordinator for each thread.

这里是catch:你不能有两个 NSPersistentStoreCoordinator 提供对同一存储的访问。但是,Marcus Zarra的核心数据手册断言, NSPersistentStoreCoordinator 是线程安全的,并将序列化I / O请求(第157页)。

So here's the catch: you can't have two NSPersistentStoreCoordinators providing access to the same store. But, Marcus Zarra's Core Data book asserts that NSPersistentStoreCoordinator is thread-safe and will serialize I/O requests (pp. 157).

有人可以为我清除这个吗?是否可能有一个第二个托管对象上下文运行在一个单独的线程上与主线程共享相同的 NSPersistentStoreCoordinator ?或者,更简洁, NSPersistentStoreCoordinator 线程安全?

Can someone clear this up for me? Is it possible to have a second managed object context running on a separate thread sharing the same NSPersistentStoreCoordinator with the main thread? Or, more succinctly, is NSPersistentStoreCoordinator thread-safe?

推荐答案

Zarra后来指出上下文锁定了存储,因此可以跨线程使用相同的NSPersistentStoreCoordinator

Zarra later points out that the context locks the store, so it is ok to use the same NSPersistentStoreCoordinator across threads.


虽然
NSPersistentStoreCoordinator不是
线程安全的,但是
NSManagedObjectContext知道如何在使用时正确地锁定

因此,我们可以附加尽可能多的
NSManagedObjectContext对象到
单个NSPersistentStoreCoordinator作为
我们想要而不用担心冲突。

Although the NSPersistentStoreCoordinator is not thread safe either, the NSManagedObjectContext knows how to lock it properly when in use. Therefore, we can attach as many NSManagedObjectContext objects to a single NSPersistentStoreCoordinator as we want without fear of collision.

这篇关于是NSPersistentStoreCoordinator线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆