简体   繁体   中英

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.

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM