Reputation: 1586
I am new to iOS dev. I am writing an iOS app that allows the user to read/write core data records. These records are to be synced to a server across http. I have a set of chained (serially) NSOperations running in a background thread that perform the sync.
The user can read/write at the same time as the sync us running. My plan is to use two managedObjectContexts within the app (both using the same persistentStoreCoordinator), one for foreground and one for background.
All background threads created by my NSOperations will run serially and will use the background MOC. All UI-based stuff will use the foreground MOC.
My question is this: is this an acceptable iOS core data pattern? Can I happily have reads/writes occurring against the same model database within these two MOCs without worrying about locking and concurrency issues?
Thanks very much.
Upvotes: 2
Views: 549
Reputation: 1904
This is a common core-data pattern and one the framework was designed to accommodate.
If you are managing the threads yourself you need to use a technique called "Thread Confinement" you can read more about it in the documentation in the section titled "Concurrency with Core Data".
In addition to thread confinement, there are also new features in iOS 5.0 designed to help manage concurrency. An NSManagedObjectContext
can now be configured with a NSManagedObjectContextConcurrencyType
. You can chose between a NSMainQueueConcurrencyType
and NSPrivateQueueConcurrencyType
.
A context with NSMainQueueConcurrencyType
runs on the main thread and can be used to serve the UI. A context with NSPrivateQueueConcurrencyType
is used for background tasks.
To use the private context you interact with it through the performBlock:
and performBlockAndWait:
methods to ensure your code is executed on the correct thread. To use the main queue context you can interact with it as normal, or if your code is not running on the main thread, by using the block methods.
These new features are not discussed in great detail in the documentation, there is some information in the section "Core Data Release Notes for iOS v5.0". However there is a much more insightful discussion in the WWDC 2012 session video: "Session 214 - Core Data Best Practices".
Upvotes: 3