I’m doing some background processing with GCD and saving some objects with Core Data. In method [self saveData] I’m creating a NSManagedObjectContext with concurrency type NSPrivateQueueConcurrencyType to perform the Core Data operations on a background thread. I’m running all my Core Data operations within performBlock.
Now, is it necessary to call [self saveData] from main thread or can I continue in the background thread I’m in (to avoid the extra call dispatch_async(dispatch_get_main_queue(), ^{});)
Like so:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
BOOL isProcessed = [self processData];
if (isProcessed) {
// Save with Core Data
[self saveData];
}
});
Or do I need to do:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
BOOL isProcessed = [self processData];
if (isProcessed) {
dispatch_async(dispatch_get_main_queue(), ^{
// Save with Core Data
[self saveData];
});
}
});
performBlock:andperformBlockAndWait:ensure that the block operations are executed on the queue specified for the context. Therefore, it does not matter on which threadperformBlock:orperformBlockAndWait:are called.The extra
dispatch_async(dispatch_get_main_queue(), ^{});is therefore not necessary if[self saveData]usesperformBlock:for all operations.