佳为好友

转:stop NSInvocationOperation

创建:2012.03.29
转:http://stackoverflow.com/questions/763003/how-to-stop-an-nsinvocationoperation
[自:NSInvocationOperation用起来很方便,但是却没有办法stop,所以在target退出的时候,不能很好的终止op。好在当执行[operation initWithTarget:self selector:@selector(myOperation:) object:operation];的时候,target(也就是self)的引用计数会自动加1,所以,可以使用下面的方法来处理。]

UPDATE: Instruments shows leaks-a-plenty when I do this. Proceed with caution! I'm keeping this here in case I'm actually on to something and someone else can figure out how to get over the leak hurdle.

Here's a twisted idea, which I'm re-trying as I type this:

Set the operation as the object for NSInvocationOperation's initWithTarget:selector:object: method. Presuming you already have a NSOperationQueue (we'll call it queue):

NSInvocationOperation *operation = [NSInvocationOperation alloc];
operation
= [operation initWithTarget:self selector:@selector(myOperation:) object:operation];
[queue addOperation:operation];
[operation release];

Note that we have to break apart the alloc into its own call. Otherwise we can't set object to operation!

Then, within your operation method, cast the object back and sprinkle checks for isCancelled as desired. For example:

 - (void)myOperation:(id)object {
   
NSInvocationOperation *operation = (NSInvocationOperation *)object;
   
if ([operation isCancelled]) return;
   
...
 
}

Make sure your selector ends with a colon back in the initWithTarget:... call, since you'll be passing in an object now.

So far, so good. Now if I can force cancelAllOperations, I'll know if this actually works. :)

+++++

posted on 2012-12-29 10:59 佳为好友 阅读(207) 评论(0)  编辑 收藏 引用 所属分类: 非UI


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2012年12月>
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345

留言簿(1)

随笔分类

搜索

最新评论

评论排行榜