dispatch_semaphore_t
:p
I wasn't aware that I could use GCD semaphores inside an NSManagedObjectContext
's -performBlock
.
I ended up creating a mutex (a binary semaphore), so that the child blocks do:
[childContext performBlock:^{
// id jsonData = GET http://myserver.com/<whateverData>
dispatch_semaphore_wait(_s, DISPATCH_TIME_FOREVER);
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:user.entity.name];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"id = %i", [jsonData[@"id"] intValue]];
NSArray *results = [childContext2 executeFetchRequest:fetchRequest error:&error];
NSManagedObject *newOrExistingObject = nil;
BOOL existsInContext = (BOOL)[results count];
if (!existsInContext) {
newOrExistingObject = [NSEntityDescription insertNewObjectForEntityForName:e.name inManagedObjectContext:childContext];
}
else {
newOrExistingObject = results[0];
}
[newOrExistingObject setValuesForKeysWithDictionary:jsonData];
[childContext obtainPermanentIDsForObjects:childContext.insertedObjects.allObjects error:nil];
[childContext save:nil];
dispatch_semaphore_signal(_s);
[mainContext performBlock:^{
[mainContext save:nil];
[saveContext performBlock:^{
[self.saveContext save:nil];
}];
}];
}};
And this did the trick