Search code examples
iosafnetworkingnsoperationnsoperationqueuegdc

How to perform an operation that requires 2 asynchronous tasks to be completed


I have 2 AFNetoworking operations fetching me data, and i have a method that requires both of them to be completed. I've read on the internet i could have an NSOperationQueue to make 1 operation dependent on another operation finishing. While this seems like a good solution in some cases, it seems like it would be difficult if I have code that isnt suited to be an NSOperation.

For example (for illustration purposes) 1. API call A gets an image A 2. API call B gets another image B 3. the maskImage function masks image B onto A

any insights would be helpful!


Solution

  • I'm not sure about what sort of code you consider ill-suited for NSOperation, but I'm wondering if your reticence to use NSOperation stems from a desire to avoid writing your own NSOperation subclass. Fortunately, using operation queues is much simpler than that. You can use NSBlockOperation or NSInvocationOperation to quickly create operations.

    I would generally use a NSBlockOperation:

    NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
        // do my image processing
        [self applyMaskToImage];
    }];
    

    Or you could use a NSInvocationOperation:

    NSOperation *completionOperation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                            selector:@selector(applyMaskToImage)
                                                                              object:nil];
    

    You can then (a) call addDependency for each of your two download operations, to make completionOperation dependent upon both; and (b) add the completionOperation to your own queue.