10
votes

I am using core data to store and fetch my data but I am facing some issue. I want to use two thread parallel for following operations:

  1. Thread one will insert data in CoreData base table(A).
  2. Thread two will fetch data from another table(B).

How I can do that?

I did some research on google and they said, we need to use multiple managed object context, But I don't know how we will use that.

1
Why do you want to use two threads in parallel? - andrewbuilder
A single persistent store coordinator will manage the process of inserting data into table A and fetching data from table B. You do not need two managed object contexts for that to work successfully. You can however create a private thread to manage the persistence process (i.e. saving data) so as not to block the User Interface. - andrewbuilder

1 Answers

21
votes

You should not access your NSManagedObjectContext on multiple threads. The NSManagedObjectContext created in your AppDelegate should only be accessed on main thread.

It implies, you should create a NSManagedObjectContext for each thread you create. Make sure to set the thread's NSManagedObjectContext's parent context as your main context.

Example : -

NSManagedObjectContext *mainContext; // = getMainContext
NSManagedObjectContext *threadContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
threadContext.parentContext = mainContext;

and then use threadContext on your thread...

You can continue your UI related fetching on main thread. Or if it is essential to have other thread for it too, create a context for it too.

To know the Core Data concurrency in depth see a tutorial

Setting Parent/Child context relationship will merge your thread's Context with main context (it's parent context).

To understand Parent/Child context relationship check this URL

Or just under this diagram -

Parent/Child context relationship.

Credits to the article URL...