Combine AFHTTPRequestOperation and NSBlockOperation (iOS)?

101 views Asked by At

I want to perform 2 requests and send a notification at the end. My code to check a sequence of the operations:

AFHTTPRequestOperation *operation1 = ...;
AFHTTPRequestOperation *operation2 = ...;
[operation1 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

            NSLog(@"asdf");
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        }];
[operation2 setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

            NSLog(@"asdf");
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        }];
NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{

        NSLog(@"123");
    }];
NSArray *operationArray = @[operation1, operation2, operation3];
for (int i = 1; i < operationArray.count; i++) {

        NSOperation *op = operationArray[i];
        [op addDependency:operationArray[i - 1]];
    }
[queue addOperations:ops waitUntilFinished:NO];

I expect the following console log:

asdf
asdf
123

But the actual result is:

asdf
123
asdf

WHY?

1

There are 1 answers

3
Wain On BEST ANSWER

From the docs

The exact execution context for your completion block is not guaranteed but is typically a secondary thread. Therefore, you should not use this block to do any work that requires a very specific execution context. Instead, you should shunt that work to your application’s main thread or to the specific thread that is capable of doing it. For example, if you have a custom thread for coordinating the completion of the operation, you could use the completion block to ping that thread.

i.e. don't rely on the completion block to be called after one operation is complete and before another starts because it isn't guaranteed to happen like that.