Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

objective c - How to stop an NSInvocationOperation?

I have an NSInvocationOperation that would download and parse a series of NSXMLDocuments in the background to my UI responsive.

My attempt at stopping the Invocation operation is to call my NSOperationQueue's cancellAllOperations. But it seems that this won't stop the invocation's execution.

Any ideas on how would I go about this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...