I'm using NSOperationQueue
, and NSOperation
for running some function on background click.
But I want to be able, when user clicks some button, stop that Operation.
How can I do it?
Something like, [currentoperation stop];
Cancel
- won't work me. I want to stop immediately.
Thanks
You should be calling the -cancel
method, and the operation itself has to support being cancelled by monitoring the isCancelled
property/keypath and safely stopping when its value becomes YES
. If the NSOperation is your own, you will probably have to create a custom subclass to implement this functionality. You cannot (safely) force an arbitrary operation to immediately stop. It has to support being cancelled.
You can't stop immediately by using anything Apple provides with NSOperation
. You can use -[cancel]
as other people have suggested here, but the current operation will still run until completion. One way of getting close to use -[isCancelled]
inside of your operation and sprinkle that throughout the code (especially in long running loops). Something like:
- (void)main {
// do a little work
if ([self isCancelled]) { return; }
// do a little more work
if ([self isCancelled]) { return; }
}
This way you'll get things stopped relatively soon.
If you're looking to really force the thread to stop, you may need to look into signal handling. There's a threaded example here. Sending a custom signal to a specific thread, you may be able to then terminate that thread in some way. This will be a lot more work, though, and is probably much more trouble than it's worth.
you use cancel
, and test whether self
(the NSOperation
) has been cancelled during execution.
来源:https://stackoverflow.com/questions/7820960/how-to-stop-current-nsoperation