I am trying to download data from an API before displaying it to the user.
Here’s what I am doing:
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
__block NSMutableArray *newImages;
dispatch_sync(concurrentQueue, ^{
newImages = [NSMutableArray array];
// images retrieved using `NSURLConnection sendSynchronousRequest`
});
dispatch_sync(dispatch_get_main_queue(), ^{
// display images to the user
});
});
My question is, since newImages is declared with __block, am I always guaranteed to have the latest newImages data when executing the second task at the main queue? If not, what’s the safest way to pass that array’s content into the second block and making sure its the latest content?
I think my data is getting messed up somewhere, hence why I am asking this.
If this looks fine, then I will post my full code for help with the whole thing in case something else is wrong.
A sketch of a solution:
The queue is a standard work queue.
The
applyUpdatesForURLs:withImages:block is guaranteed to run after all images have been downloaded, by virtue of being enqueued in a serial queue after the image download blocks.There’s no synchronization problems with
imagesbecause all code working with it runs serially not concurrently.And the UI update ultimately occurs on the main thread.