1

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!

jfisk
  • 6,125
  • 20
  • 77
  • 113
  • Why do you say your code isn't suited for an NSOperation? Also, aren't you complicating things unnecessarily? Just a couple of flags should suffice, no? – maroux Jun 02 '13 at 06:01
  • Why is this not suited to a `NSOperation`? I'd just do a simple `NSOperation *completionOperation = [NSBlockOperation operationWithBlock:^{ ... }];` and then add your dependencies to that operation. This seems precisely like something suited for an `NSOperation` (you certainly don't want to be doing complex image processing on the main queue). – Rob Jun 02 '13 at 06:02
  • @Rob NSBlockOperation looks great, didnt know it existed. – jfisk Jun 02 '13 at 06:04

1 Answers1

3

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.

Rob
  • 415,655
  • 72
  • 787
  • 1,044