Search code examples
iphonemultithreadingiosibaction

How to tell iPhone OS function to stop/cancel?


I have an action which begins when the user taps a button on the screen (e.g. "Import"). At the same time, a UIToolbar appears on the bottom of the screen which gives the user the option to cancel this action. How can I properly send a cancel message to the initial function? If the user hits "Cancel," I do not want the "Import" to continue. In theory I could set it up as a separate thread (which I could then kill), but I am not sure what is the proper way to do this so that it could clean up after itself. What are some other strategies to be able to "kill" a function which the user has already begun?


Solution

  • Create a separate operation using something like:

    NSOperationQueue* queue = [[[NSOperationQueue alloc] init] autorelease];
    [queue addOperation: [[[NSInvocationOperation alloc] initWithTarget: self 
          selector: @selector(_backgroundWorker) 
          object: nil] autorelease]];
    

    This way _backgroundWorker will be executed without stopping main UI thread.

    One Cancel button is pressed, set some internal variable and check its value inside _backgroundWorker.