Reputation: 1675
I am developing an application that uses Core Data for internal storage. This application has the following functionalities :
I have read through a lot and a lot of documentation that there are several patterns to follow in order to apply multithreading with Core Data :
I tried the 3 mentioned approaches and i realized that 2 last ones work fine. However i am not sure if these approaches are correct when talking about performance.
Is there please a well known performant pattern to apply in order to make a robust application that implements the mentioned functionalities ?
Upvotes: 1
Views: 397
Reputation: 4339
rokridi,
In my Twitter iOS apps, Retweever and #chat, I use a simple two MOC model. All database insertions and deletions take place on a private concurrent insertionMOC
. The main MOC merges through -save:
notifications from the insertionMOC
and during merge processing emits a custom UI update notification. This lets me work in a staged fashion. All tweets come in to the app are processed on the background and are presented to the UI when everything is done.
If you download the apps, #chat's engine has been modernized and is more efficient and more isolated from the main thread than Retweever's engine.
Anon, Andrew
Upvotes: 1
Reputation: 14477
As per apple documentation use Thread Confinement to Support Concurrency Creating one managed object context per thread. It will make your life easy. This is for when you are parsing large data in background and also fetching data on main thread to display in UI.
About the merging issue there are some best ways to do them. Never pass objects between thread, but pass object ids to other thread if necessary and access them from that thread, for example when you are saving data by parsing xml you should save them on current thread moc and get the ids of them, and pass to UI thread, In UI thread re fetch them.
You can also register for notification and when one moc will change you will get notified by the user info dictionary which will have updated objects, you can pass them to merge context method call.
Upvotes: 1
Reputation: 933
Apple recommends using separate context for each thread.
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.
See the apple Documentation
Upvotes: 1