【问题标题】:Get specific NSOperation from NSOperationQueue从 NSOperationQueue 获取特定的 NSOperation
【发布时间】:2016-01-14 14:57:46
【问题描述】:

你好,

在我的应用程序中,我创建 NSOperations 并将它们添加到 NSOperationQueue。 有时,我想从我的操作队列中取消一些特定的操作,这就是我为我的 NSOperation 子类定义一个标识符属性的原因:

@property (nonatomic, assign) NSString *identifier;

但是当我循环进入队列的操作并且我想将我的操作的标识符与我想要获取的操作的标识符进行比较时,我得到一个 EXC_BAD_ACCESS 指出 if 条件:

for (MyCustomNSOperationClass *operation in self.myOperationQueue.operations)
{
     NSString *identifier = [self getRelatedIdentifier];
     if ([operation.identifier isEqualToString:identifier])
     {
           [operation cancel];
     }
}

操作的标识符应该类似于33a37fb0-8f77-0132-6c0b-5254005d9147,但当它崩溃时,它类似于0x7be4af00(当我使用po operation.identifier 时)。 我说当它崩溃时,因为它并不总是崩溃并且当它不崩溃时,那么标识符是正确的(我不确定是否超级清楚......)。

由于我是 NSOperation 的新手,我想知道是否有其他方法可以实现我想做的事情?

提前致谢!

【问题讨论】:

    标签: ios nsoperation nsoperationqueue


    【解决方案1】:

    最好有一个数组operations:[MyCustomNSOperationClass](或字典operations:[String: MyCustomNSOperationClass])来保存对队列中所有操作的引用,然后直接取消它而不在队列中搜索它。

    【讨论】:

    • 我刚刚尝试过,但我仍然遇到完全相同的问题。
    • 好的,当我使用字典时它终于可以工作了。谢谢伊斯梅尔!
    【解决方案2】:

    您的问题是您没有复制操作,并且队列可能会在循环时被修改。

      NSArray<MyCustomNSOperationClass *> *operations = operationQueue.operations.copy;
    
      for (MyCustomNSOperationClass *operation in operations) {
    
        if (!operation.isFinished && [operation.identifier isEqualToString:self.cancelIdentifier]) {
          [operation cancel];
        }
    
      }
    

    您不应该依赖 OperationQueue 的状态来执行您的操作并将其存储在字典中,正如 Ismail 所建议的那样是一个可行的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多