7

从文档:

一个操作对象一次最多只能在一个操作队列中,如果该操作已经在另一个队列中,则此方法会抛出 NSInvalidArgumentException 异常。同样,如果操作当前正在执行或已经完成执行,则此方法会引发 NSInvalidArgumentException 异常。

那么如何检查是否可以安全地将 NSOperation 添加到队列中?

我知道的唯一方法是添加操作,然后如果操作已经在队列中或之前执行,则尝试捕获异常。

4

2 回答 2

17

NSOperationQueue对象有一个名为operations.

如果您对队列有参考,则很容易检查。

您可以检查操作的 NSArray 是否包含您的NSOperation类似内容:

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");

或者您可以迭代所有对象:

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

告诉我这是否是你要找的。

或者,NSOperation对象有几个属性可以让你检查它们的状态;如:isExecuting, isFinished, isCancelled, 等...

于 2011-03-07T08:47:24.880 回答
4

当您将NSOperation对象添加到NSOperationQueue时,NSOperationQueue 会保留该对象,因此NSOperation的创建者可以释放它。如果你坚持这个策略,NSOperationQueues将永远是他们的NSOperation对象的唯一所有者,所以你将无法将NSOperation对象添加到任何其他队列中。

如果您在将单个NSOperation对象添加到队列后仍想引用它们,则可以使用NSOperationQueue- (NSArray *)operations方法来实现。

于 2011-03-07T08:49:37.220 回答