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:
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.
Most apps need just a single managed object context. The default configuration in most Core Data apps is a single managed object context associated with the main queue. Multiple managed object contexts make your apps harder to debug; it's not something you'd use in every app, in every situation.
You cannot pass NSManagedObjects between multiple contexts, but you can pass NSManagedObjectIDs and use them to query the appropriate context for the object represented by that ID.
A managed object context represents a single object space, or scratch pad, in a Core Data application. A managed object context is an instance of NSManagedObjectContext . Its primary responsibility is to manage a collection of managed objects.
There are multiple ways to use Core Data and a NSManagedObjectContext on a background thread. One way is the performBackgroundTask(_:) method on an NSPersistentContainer : // Spawns a new thread and creates a background // managed object context to perform operations // in the background persistentContainer.
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 -
Credits to the article URL...
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