iOS - 如何检查NSOperation是否在NSOperationQueue中? [英] iOS - How to check if an NSOperation is in an NSOperationQueue?

查看:147
本文介绍了iOS - 如何检查NSOperation是否在NSOperationQueue中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自文档:



操作对象一次最多只能包含一个操作队列如果操作已在另一个队列中,则此方法抛出NSInvalidArgumentException异常。类似地,如果操作当前正在执行或已经完成执行,则此方法抛出NSInvalidArgumentException异常。



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



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

解决方案

NSOperationQueue 对象有一个名为的属性



如果您有对队列的引用,则很容易检查。



您可以检查NSArray操作是否包含您的 NSOperation ,如下所示:

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

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

[queue addOperation:operation];

if([队列操作] containsObject:operation])
NSLog(@操作在队列中);
else
NSLog(@操作不在队列中);

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

  for(NSOperation * op in [queue operations])
if(op == operation){
NSLog(@Operation is the queue) ;
}
else {
NSLog(@操作不在队列中);
}

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

或者, NSOperation 对象有几个允许你检查其状态的属性;例如: isExecuting isFinished isCancelled 等。 ..


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

这篇关于iOS - 如何检查NSOperation是否在NSOperationQueue中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆