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

两盒软妹~` 提交于 2019-12-04 23:22:38

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/5217504/ios-how-to-check-if-an-nsoperation-is-in-an-nsoperationqueue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!