iOS – 如何检查NSOperation是否在NSOperationQueue中?

来自文档:

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

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

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

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对象具有几个允许您检查其状态的属性; 例如: isExecutingisFinishedisCancelled等…

当您将NSOperation对象添加到NSOperationQueue时NSOperationQueue会保留该对象,因此NSOperation的创建者可以释放它。 如果您遵循此策略, NSOperationQueues将始终是其NSOperation对象的唯一所有者,因此您将无法将NSOperation对象添加到任何其他队列。

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