Cocoa 和摆脱无限循环
我的基本想法是单击一个按钮并进入无限循环。我打算单击另一个按钮来停止并摆脱这个循环。问题是,一旦我进入无限循环,我的第二次点击就永远不会被检测到,所以我无法退出。关于如何让它发挥作用有什么想法吗?非常感谢。
-(IBAction) startButton {
while (1) {
// code
}
}
-(IBAction) stopButton {
NSLog(@" out of loop now");
}
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");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果无法使用计时器,则需要使用后台线程、
NSOperation
或 Grand Central Dispatch 任务。If you can’t use a timer, you need to use a background thread,
NSOperation
or Grand Central Dispatch task.为什么不使用 NSOperation 和 NSOperationQueue?通过循环的每一行,您都可以检查它是否被取消和中断。这样,主线程(您的 UI 更新和响应)就不会冻结,您的应用程序也不会打沙滩球。
需要意识到的重要一点是,如果您将主线程绑定在循环中,则在循环结束之前您将不会获取进一步的事件,这意味着没有按钮单击取消。
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.
你想让你的循环做什么?也许您可以使用
NSTimer
。What do you want your loop to do? Maybe you could use an
NSTimer
.