Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop pinwheel of death in infinite loop Objective C

I am writing a simple timer program for myself in objective c for my mac. The timer counts down properly, but I get the spinning pinwheel of death. How can I make the pinwheel go away? I think its because I have an infinite loop but there must be someway to bypass it.

I have an IBAction that triggered on a button click (the button is start). And from there, it calls another function that does the work.

Here is my IBAction:

- (IBAction)timerStart:(id)sender {
    self.timerDidPause = NO;
    [self timerRunning];
}

And here is timerRunning:

- (void)timerRunning {
for (;;) {
    usleep(1000000);
    if (self.timerDidPause == YES) {

    }
    else {
        if (self.seconds == 0) {
            if (self.minutes == 0) {
                [self timerDone];
                break;
            }
            else {
                self.seconds = 59;
                self.minutes = self.minutes - 1;
                [self formatTimerLabel:self.hours :self.minutes :self.seconds];
            }
        }
        else {
            self.seconds = self.seconds - 1;
            [self formatTimerLabel:self.hours :self.minutes :self.seconds];
        }
    }
}
}

In this function, the function formatTimerLabel is called so here is that:

- (void)formatTimerLabel:(int)hours
                    :(int)minutes
                    :(int)seconds {
NSString *minuteString = [[NSString alloc] init];
NSString *secondString = [[NSString alloc] init];
if (minutes < 10) {
    minuteString = [NSString stringWithFormat:@"0%d", minutes];
}
else {
    minuteString = [NSString stringWithFormat:@"%d", minutes];
}
if (seconds < 10) {
    secondString = [NSString stringWithFormat:@"0%d", seconds];
}
else {
    secondString = [NSString stringWithFormat:@"%d", seconds];
}
[self.timerLabel setStringValue:[NSString stringWithFormat:@"%d:%@:%@", hours, minuteString, secondString]];
[self.timerLabel display];
}
like image 746
jamespick Avatar asked Jun 21 '13 18:06

jamespick


1 Answers

You're causing the UI thread to hang with your loop. After a couple of seconds of that, the OS switches the cursor to a pinwheel.

You need to look into NSTimer and the Timer Programming Guide to schedule the timer to run outside of the UI thread.

like image 107
Carl Norum Avatar answered Nov 05 '22 20:11

Carl Norum