如何取消使用addOperationWithBlock创建的操作? [英] how to cancel out of operation created with addOperationWithBlock?

查看:99
本文介绍了如何取消使用addOperationWithBlock创建的操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NSOperationQueue的addOperationWithBlock。从块内,我该如何检查是否应该取消操作?或访问任何NSOperation属性/方法?

I'm using NSOperationQueue's addOperationWithBlock. From within the block, how do I check to see if I'm supposed to cancel the operation? Or access any NSOperation properties/methods?

[myOperationQueue addOperationWithBlock: ^{

  while ( /* long running loop */ )
  {
      // how to determine here if I need to cancel?
      // for that matter, access any NSOperation properties/methods?

  }

}];

使用NSBlockOperation是更好的方法吗?

Is the better way to do this to use a NSBlockOperation?

推荐答案

更好的解决方案可能是使用 NSBlockOperation 并将其添加到队列而不是原始块。你可以这样做:

A better solution might be to use NSBlockOperation and add that to the queue instead of a raw block. You could do something like:

__block NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
  while(![operation isCancelled]){
    //Some long operation
  }
}];

[[self queue] addOperation:operation];

这可以让你使用块,同时让你对操作有更多的控制......还有一些更多 NSOperation niceties(例如添加完成块的功能)。

This lets you use blocks while giving you a little more control over the operation... and a few more NSOperation niceties as well (like the ability to add completion blocks, for example).

这篇关于如何取消使用addOperationWithBlock创建的操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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