Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - How to check if an NSOperation is in an NSOperationQueue?

From the docs:

An operation object can be in at most one operation queue at a time and this method throws an NSInvalidArgumentException exception if the operation is already in another queue. Similarly, this method throws an NSInvalidArgumentException exception if the operation is currently executing or has already finished executing.

So how do I check if I can safely add an NSOperation into a queue?

The only way I know is add the operation and then try to catch the exception if the operation is already in a queue or executed before.

like image 394
Bryan Chen Avatar asked Mar 07 '11 08:03

Bryan Chen


2 Answers

NSOperationQueue objects have a property called operations.

If you have a reference to you queues it is easy to check.

You can check if the NSArray of operations contains your NSOperation like this:

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

NSOperation *operation = [[NSOperation alloc] init];

[queue addOperation:operation];

if([queue operations] containsObject:operation])
    NSLog(@"Operation is in the queue");
else
    NSLog(@"Operation is not in the queue");

Or you can iterate on all the objects:

for(NSOperation *op in [queue operations])
    if (op==operation) {
        NSLog(@"Operation is in the queue");
    }
    else {
        NSLog(@"Operation is not in the queue");
    }

Tell me if this is what you are looking for.

Alternatively, NSOperation objects have several properties that allow you to check their state; such as: isExecuting, isFinished, isCancelled, etc...

like image 144
Zebs Avatar answered Oct 17 '22 16:10

Zebs


When you add an NSOperation object to a NSOperationQueue, the NSOperationQueue retains the object, so the creator of the NSOperation can release it. If you keep with this strategy, NSOperationQueues will always be the only owner of their NSOperation objects, so you won't be able to add an NSOperation object to any other queue.

If you still want to reference individual NSOperation objects after they've been added to the queue, you can do so using the NSOperationQueue's - (NSArray *)operations method.

like image 42
James Bedford Avatar answered Oct 17 '22 15:10

James Bedford