I am setting up Core Data in an application using UIManagedDocument. I am then adding around 1000 NSManagedObject(s) to the data base in a loop. I am initially processing the data for the objects in a background thread using:
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(backgroundQueue, ^{
// PROCESS OBJECTS HERE
...
...
Before adding them to Core Data from the background thread:
NSManagedObjectContext *moc = [[self managedDocument] managedObjectContext];
[moc performBlock:^{
// ADD TO CORE DATA
...
...
using:
// CREATE
Fruit *fruit = [NSEntityDescription insertNewObjectForEntityForName:@"Fruit" inManagedObjectContext:context];
// POPULATE
[fruit setName:name];
[fruit setAge:age];
[fruit setType:type];
...
My question is:
Doing the above for 1000+ objects is currently taking about 2.2secs, I am not doing any saves on Core Data until all the objects have been inserted so its all done in memory with no I/O overhead. As you can see above all my processing is done on the background thread, but when I come to insert the new object into Core Data I have to use performBlock: to make sure the insert is done back on the main thread where the UIManagedDocument was originally created.
What I would like to know is, is there a way to speed up inserting the objects, maybe by "batching" a number of NSManagedObjects together and add them in one hit, or is that just going to take the same amount of time as what I am doing now (its still adding 1000+ objects).
I did read something about creating a new context and then merging that with the NSManagedDocument context, but I am not sure if thats appropriate or how to do it if it is. Any help / information would be much appreciated.