Note that there are some explanatory texts on larger screens.

plurals
  1. POWait until multiple networking requests have all executed - including their completion blocks
    primarykey
    data
    text
    <p>I have multiple operations (they're AFNetworking requests) with completion blocks that takes some time to execute, and a Core Data object that needs to be saved at the end of all the requests.</p> <pre><code>MyCoreDataObject *coreDataObject; AFHTTPRequestOperation *operation1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1]; [operation1 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { coreDataObject.attribute1 = responseObject; sleep(5); }]; [operation1 start]; AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request1]; [operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { coreDataObject.attribute2 = responseObject; sleep(10); }]; [operation1 operation2]; [context save:nil]; </code></pre> <p>Of course, this does not work as I want because the requests are asynchronous. I tried adding an NSOperationQueue like so:</p> <pre><code>NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init]; [operationQueue setMaxConcurrentOperationCount:2]; AFHTTPRequestOperation *operation1 = [[AFHTTPRequestOperation alloc] initWithRequest:request1]; [operation1 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { coreDataObject.attribute1 = responseObject; sleep(5); }]; [operationQueue addOperation:operation1]; AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] initWithRequest:request1]; [operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { coreDataObject.attribute2 = responseObject; sleep(10); }]; [operationQueue addOperation:operation2]; [imageQueue waitUntilAllOperationsAreFinished]; [context save:nil]; </code></pre> <p>This looks a bit better. Using <code>waitUntilAllOperationsAreFinished</code>, my queue blocks the current thread until my requests are finished, but not until my success Blocks are finished, which is really what I need.</p> <p>Any ideas on how to achieve this in a good way?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload