After trying out AFIncrementalStore I've decided to do most of the work manually to have more control over what happens and when.
Object structure I have looks like this. "products" relationship is an ordered one.
Here's the code that runs inside a NSOperation
NSManagedObjectContext* childContext = [[NSManagedObjectContext alloc] initWithConcurrencyType: NSPrivateQueueConcurrencyType];
childContext.parentContext = self.parentManagedObjectContext;
[childContext performBlockAndWait: ^
{
DashboardViewModel* dashboardViewModel = [NSEntityDescription insertNewObjectForEntityForName: @"DashboardViewModel"
inManagedObjectContext: childContext];
NSMutableOrderedSet* products = [NSMutableOrderedSet orderedSetWithCapacity: productRepresentations.count];
for (NSDictionary* rawProductRepresentation in productRepresentations)
{
Product* product = [NSEntityDescription insertNewObjectForEntityForName: @"Product"
inManagedObjectContext: childContext];
product.dashboardViewModel = dashboardViewModel;
[products addObject: product];
}
dashboardViewModel.products = products;
NSError* saveError = nil;
if (![childContext save: &saveError])
NSLog(@"Error: %@", saveError);
//Save parent context to push changes to persistent store
[self.parentManagedObjectContext performBlock: ^
{
NSError* saveParentError = nil;
if (![childContext.parentContext save: &saveParentError])
NSLog(@"Error: %@", saveParentError);
}];
}];
Seems correct to me but I always get an error when saving parent context that says "Dangling reference to an invalid object.”</p>
Any suggestions?