如何取消NSBlockOperation [英] How to cancel NSBlockOperation

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

问题描述

我有一个长时间运行的循环,我想使用NSOperation在后台运行.我想使用一个块:

I have a long running loop I want to run in the background with an NSOperation. I'd like to use a block:

NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
   while(/* not canceled*/){
      //do something...
   }
}];

问题是,如何检查它是否已取消.该块不带任何参数,并且operation在被块捕获时为nil.没有办法取消块操作吗?

The question is, how to I check to see if it's canceled. The block doesn't take any arguments, and operation is nil at the time it's captured by the block. Is there no way to cancel block operations?

推荐答案

Doh.亲爱的未来的google员工:当然,operation由区块复制时为零,但是没有可以复制.可以使用__block进行限定,如下所示:

Doh. Dear future googlers: of course operation is nil when copied by the block, but it doesn't have to be copied. It can be qualified with __block like so:

//THIS MIGHT LEAK! See the update below.
__block NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
   while( ! [operation isCancelled]){
      //do something...
   }
}];

更新:

UPDATE:

在进一步的冥想中,我想到这将在ARC下创建一个保留周期.在ARC中,我相信__block存储会保留.如果是这样,我们就麻烦了,因为NSBlockOperation还保留了对传入块的强引用,现在该块对操作有了强引用,而操作又对传入块有强引用,即……

Upon further meditation, it occurs to me that this will create a retain cycle under ARC. In ARC, I believe __block storage is retained. If so, we're in trouble, because NSBlockOperation also keeps a strong references to the passed in block, which now has a strong reference to the operation, which has a strong reference to the passed in block, which…

这不太优雅,但是使用显式的弱引用应该打破循环:

It's a little less elegant, but using an explicit weak reference should break the cycle:

NSBlockOperation *operation = [[NSBlockOperation alloc] init];
__weak NSBlockOperation *weakOperation = operation;
[operation addExecutionBlock:^{
   while( ! [weakOperation isCancelled]){
      //do something...
   }
}];

任何有想法寻求更优雅解决方案的人,请发表评论!

Anyone that has ideas for a more elegant solution, please comment!

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

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