I have just began learning core data programming. I tried to make an example in which there is a table view that displays a list of persons (properties : first name, last name). The table view relies on an NSFetchResultController to display the list of persons.
I followed the nested contexts pattern as follows :
Root Context (NSPrivateQueueConcurrencyType) <---> Main Context (NSMainQueueConcurrencyType) <---> Children Contexts (NSPrivateQueueConcurrencyType).
The children contexts are used to perform huge insertion/fetch (with perormBlock: method). When i try to perform a huge insertion (about 5000 rows), save the child context then the main context then the root context, i see that my UI is blocked until the save is finished.
Could any one please tell me what is the best solution to adopt in order to make a performant application ? Could anyone please provide me a nice simple code that show how to make huge fetch/insertion in background without blocking the UI?
[_indicator startAnimating];
NSManagedObjectContext *aContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
aContext.parentContext = [[SDCoreDataController sharedInstance] mainManagedObjectContext];
[aContext performBlock:^{
NSError *error;
for (int i = 0; i < 5000; i++)
{
FootBallCoach *backgroundCoach = [NSEntityDescription insertNewObjectForEntityForName:@"FootBallCoach" inManagedObjectContext:aContext];
backgroundCoach.firstName = [NSString stringWithFormat:@"José %i",i];
backgroundCoach.lastName = [NSString stringWithFormat:@"Morinho %i",i];
backgroundCoach.cin = [NSString stringWithFormat:@"%i",i];
if (i % 50 == 0)
{
[aContext save:&error];
[aContext reset];
}
}
[[SDCoreDataController sharedInstance] saveMainContext];
[[SDCoreDataController sharedInstance] saveRootContext];
dispatch_async(dispatch_get_main_queue(), ^{
[_indicator stopAnimating];
[self refreshCoaches:nil];
});
}];