I'm a beginner with Grand Central Dispatch (GCD) and Core Data, and I need your help to use Core Data with CGD, so that the UI is not locked while I add 40.000 records to Core Data.
I know that CD is not thread safe, so I have to use another context, and then save the data and merge contexts, as far as I was able to understand from some articles.
What I couldn't do yet, is put the pieces together.
So, in my code, I need your help on how to to that.
I have:
/*some other code*/
for (NSDictionary *memberData in arrayWithResult) {
//get the Activities for this member
NSArray *arrayWithMemberActivities = [activitiesDict objectForKey:[memberData objectForKey:@"MemberID"]];
//create the Member, with the NSSet of Activities
[Members createMemberWithDataFromServer:memberData
andActivitiesArray:arrayWithMemberActivities
andStaffArray:nil
andContactsArray:nil
inManagedObjectContext:self.managedObjectContext];
}
How can I transform this to work on the background, and then, when done saving, save the data and update the UI, without blocking the UI while saving the 40.000 objects?
So the selected answer for this is from nearly 2 years ago now, and there's a few issues with it:
--Edit--
Looking further into #3 - waitUntilDone:YES isn't a valid methodSignature for managed context objects, so how does that even work?
Here's a good example for you to try. Feel free to come back if you have any questions:
And in response to the context save notification:
And don't forget to remove the observer from the notification center once you are done with the background thread context.
Here's a snippet which covers GCD and UI in it's simplest terms. You can replace doWork with your code that does the CoreData work.
Concerning CD and thread safety, one of the nice parts about GCD is you can sections off areas of your application (subsystems) to synchronize and ensure they get executed on the same queue. You could execute all CoreData work on a queue named com.yourcompany.appname.dataaccess.
In the sample, there's a button which invokes the long running work, a status label, and I added a slider to show I can move the slider while the bg work is done.
Much easier way to do it than attach the persistent store coordinator to a new context, which is not thread safe either, btw.
Great tutorial on how to use multi-context Core Data:
http://www.cocoanetics.com/2012/07/multi-context-coredata/
Adding another source of info you can check
ThreadedCoreData
the Sample Code of Apple's iOS Developer Library, which have been recently updated (2013-06-09)
This blog post has a detailed description on Core Data concurrency and sample code: http://www.duckrowing.com/2010/03/11/using-core-data-on-multiple-threads/