Reputation: 913
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:
NSOperation
to create custom objects for each request type, then use introspection on the objects retrieved from the operations
propertyNSBlockOperation
and add a description propertyAm I missing some other obvious way to do this?
Upvotes: 1
Views: 2952
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
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
Reputation: 1145
You could use priorities.
[NSBlockOperation setPriority:NSOperationQueuePriority]
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