I’m writing some code to sync objects between a client and a server. It involves a bunch of HTTP calls (which I’m not making myself but using the Parse library) with blocks for callbacks. I want to wait until a set of these calls are done, then take a further action. Along the way I need to store the result of each call somewhere.
The easiest way I can think of is to keep a counter and a collection — something like an NSMutableArray or NSMutableSet. Each time an HTTP operation finishes I store its result in the collection and increment the counter. Then I check the counter, and if it equals the total number of operations I proceed to the next step. (I’m proposing a counter rather than the size of the collection since I may not need to store an object for each HTTP call.)
But I’m guessing I get into thread safety issues: what happens when two calls return simultaneously and both try and add to the collection and/or increment the counter?
What’s the solution here?
Thanks!
This is what GCD is designed to handle. What you want are called Dispatch Groups. See the GCD Reference and look at the section “Using Dispatch Groups.” With a dispatch group, you submit various blocks as part of a group, and a “notify” block that is called when the group completes, no matter how they’re scheduled.