Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

shakeman0

macrumors 6502a
Original poster
Jul 20, 2009
632
22
I have an application where the user inputs how many times the application should repeat an action. The user inputed value is taken and used in a while loop that repeats the action the user specified amount of times. The process can be very long and I would like to have a button that would allow the user to end the process. I have moved the repeat process to a secondary thread (NSThread) so that the user can continue to interact with the user interface while the process is running. I'm having trouble stopping the repeat process when the user presses the "Stop" button. What is the best way to allow my main thread to communicate to a secondary thread that it needs to stop a while loop running in it? Any help would be greatly appreciated.

Thanks,

Sam

This didn't seem to work for me... I declared two atomic NSNumbers using @property (atomic, retain). They are both set to have an integer value of 0. Here is my loop that runs in the method run in the secondary thread:

Code:
 int i = 0;

 while (i < timesToRun && [numberOne intValue] == 0) { 
 [self doSomething]; 
 numberOne = numberTwo;
 i++; 
 }
My stop button calls a method that changes the integer value of numberTwo to "1". For some reason this isn't stopping the loop. Am I doing something incorrectly?
 
You're reinventing the wheel, badly. If you're using NSThread or NSOperation, you send cancel and the loop sends isCancelled to check if it should stop.
 
You're reinventing the wheel, badly. If you're using NSThread or NSOperation, you send cancel and the loop sends isCancelled to check if it should stop.

Thank you for the reply. I wasn't aware of isCancelled. Unfortunately, it doesn't seem to be canceling the thread either...
 
Thank you for the reply. I wasn't aware of isCancelled. Unfortunately, it doesn't seem to be canceling the thread either...

Typical explanation would be that you send the message to the wrong object. Put some NSLog statements in the right places, where the thread is supposed to be cancelled, and where you check for it being cancelled.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.