ZionKing
ZionKing

Reputation: 326

Cocoa and getting out of infinite loops

The basic idea I have is to click on one button and enter an infinite loop. I plan to click on another button to stop and get out of this loop. Trouble is once I get into the infinite loop, my second click is never detected so I can't get out. Any idea's on how I can get this to work ? Thanks a ton.

-(IBAction) startButton {
  while (1) { 
    // code
  }     
}

-(IBAction) stopButton {
  NSLog(@" out of loop now");
}

Upvotes: 1

Views: 315

Answers (3)

Joshua Nozzi
Joshua Nozzi

Reputation: 61228

Why not use NSOperation and NSOperationQueue? Each trip through the loop, you can check if it isCanceled and break. That way, the main thread (on which your UI updates and responds) won't freeze up and your app won't beach ball.

The important thing to realize is, if you tie up the main thread in a loop, you won't get further events until the loop ends, which means no button-click-to-cancel.

Upvotes: 1

Jens Ayton
Jens Ayton

Reputation: 14558

If you can’t use a timer, you need to use a background thread, NSOperation or Grand Central Dispatch task.

Upvotes: 2

jessecurry
jessecurry

Reputation: 22116

What do you want your loop to do? Maybe you could use an NSTimer.

Upvotes: 1

Related Questions