views:

240

answers:

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)

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.

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).

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?

+2  A: 

Is it possible to have a second managed object context running on a separate thread sharing the same NSPersistentStoreCoordinator with the main thread?

Yes! I recommend you to read the corresponding section of Zarra's book carefully before venturing into multi-threaded access to CoreData.

Or, more succinctly, is NSPersistentStoreCoordinator thread-safe?

Well, the word `thread-safe' has shades of meaning in the Apple doc, so be very careful! See this blog article for a nice explanation.

Yuji
I just ordered Zarra's book, but in the meantime, how about the managed context? Can I have a singleton context shared by multiple threads?
Remus Rusanu
No, you need a separate context for each thread, but they can be linked to the same coordinator. If you order Pragmatic Programmer books directly from them, then you can download the ebook immediately while the paper one ships.
gerry3
+8  A: 

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

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.

gerry3