One way to do this properly is with NSThread. You can very easily create a new thread which just calls your calculation method. In your calculation method, you check a variable to see if it's been aborted. Meanwhile on the main thread, the UI remains responsive and you can use an event (a key press or button press) to set the variable which is checked on the other thread. I might look something like this:
- (void)startCalculations
{
[NSThread detachNewThreadSelector:@selector (runCalculations)
toTarget:myObject
withObject:nil]; // Or you can send an object if you need to
}
Then in the code for myObject
:
- (void)runCalculations
{
for (int i = 0; (i < maxWhatever) && (!stopCalculations); i++)
{
... do one iteration of your calculation
}
}
Then when your UI code gets the proper key or button press, you simply tell myObject
to set stopCalculations
to YES
.
[myObject setStopCalculations:YES];
I should note that there are other ways to do this, like using GCD or pthreads directly, but this is a very simple way to just run a single method on another thread, and all the details of starting and tearing down the thread are taken care of for you.