Craig Watkinson
Craig Watkinson

Reputation: 913

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?

Upvotes: 1

Views: 2952

Answers (3)

CodeReaper
CodeReaper

Reputation: 6155

I would say the proper way would be to subclass either NSOperation or NSBlockOperation and in this subclass implement an -(BOOL)isEqual:(id)object method so you can compare the operations you find in the NSOperationQueue's operations property. That way you should be able to use the builtin [operationA addDependency:operationB];

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 386038

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.

Upvotes: 2

estobbart
estobbart

Reputation: 1145

You could use priorities.

[NSBlockOperation setPriority:NSOperationQueuePriority]

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html

Then when you enumerate through the operations you could check the priority levels and add them as a dependency or not. You may not even need to check them and just set the priority level of your operation appropriately.

Upvotes: 1

Related Questions