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

标签 iphone objective-c ios nsoperation nsoperationqueue

来自文档:

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.

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

我知道的唯一方法是添加操作,然后在操作已经在队列中或之前执行时 try catch 异常。

最佳答案

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

关于iphone - iOS - 如何检查 NSOperation 是否在 NSOperationQueue 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5217504/

相关文章:

objective-c - iAd 横幅 View 委托(delegate)未调用方法

ios - UIImageView 不会动画,只有静态图像

ios - UICollectionView 不渲染单元格 - 没有代码只有 Storyboard

ios - iOS 中从右向左打开滑动菜单导航

iphone - 我可以更改 UITextView 上自动检测到的链接的颜色吗?

ios - Pod 无法在 iPhone 上运行

ios - UNCalendarNotificationTrigger 每小时触发器返回错误的触发日期

ios - UIView ClipsToBounds 不起作用

objective-c - 使用一个版本的 Xcode 构建时 iOS 会崩溃,而使用另一版本则不会崩溃

ios - Swift 如何从 UITableViewRowAction 获取访问功能