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 NSPersistentStoreCoordinator
s 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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With