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");
}
If you can’t use a timer, you need to use a background thread, NSOperation
or Grand Central Dispatch task.
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.
What do you want your loop to do? Maybe you could use an NSTimer
.
精彩评论