Search code examples
objective-ciosmultithreadingnsoperationnsoperationqueue

Adding NSOperation dependencies to operations already in an NSOperationQueue


I want to implement some background network requests using an NSOperationQueue. I have a couple of different requests that would be added to the queue by different parts of the code, and one of these will run more regularly than the other.

I already implement this using GCD so I have blocks of code, therefore I was planning to simply use the NSBlockOperation method blockOperationWithBlock:^{...} and not create sub classes of NSOperation.

This problem is that I would like to create a dependency between the requests. If the queue already has an NSBlockOperation for requestA then I want to add a dependency to it when I create NSBlockOperation for requestB. This is trivial when creating the operations at the same time, but I can't find an easy way to determine what operations already exist in the queue.

NSOperationQueue has an operations property, so I can retrieve a list of the operations themselves, but how do I determine which operation is which? I don't see a name/description property that I can use.

The options I can think of are:

  1. Subclass NSOperation to create custom objects for each request type, then use introspection on the objects retrieved from the operations property
  2. Subclass NSBlockOperation and add a description property

Am I missing some other obvious way to do this?


Solution

  • Add an instance variable holding the most recent requestA operation. Clear it out at the end of the requestA block. E.g.

    _requestA = [NSBlockOperation blockOperationWithBlock:^{
        // Normal requestA code here.
        // ...
    
        // Assuming you create all requestA and requestB instances on the main thread...
        dispatch_async(dispatch_get_main_queue(), ^{ _requestA = nil; });
    }];
    

    Then when you create a requestB, you can give it the latest requestA as a dependency, if there is still one to be used.