有没有办法编写一个 NSTimer 以便它只是暂停程序一秒钟?
尝试更改按钮图片,请稍等,然后再更改回来。没有太多运气试图让它工作,所以有没有办法只暂停程序一秒钟,而不让计时器实际执行任何东西,并且程序不继续执行代码?
Trying to change a button pic, wait a second, then change back. Not having much luck trying to get that to work, so is there a way to just pause the program for a second, without having a timer actually executing anything, and without the program going on with the code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将更改代码放入方法中,然后从更改方法中调用:
Try putting your change back code in a method, and call from your change method:
你可以调用
Or,更现代的:
或者,更现代的:
或者,更现代的、更可可的:
所有这些都会停止当前线程。如果您的应用程序只有一个线程,那么这意味着它将停止您的整个应用程序。在睡眠期间它将不会响应任何用户界面事件。
NSObject 参考显示了一个名为 performSelector:withObject:afterDelay:。此方法通过在运行循环中调度它来在指定的延迟后执行选择器。这意味着运行循环继续循环并处理事件、触发计时器、耗尽自动释放池、发送更多预定消息等等。
在这种特殊情况下,最好在运行循环中安排选择器(提供将图像更改回来的选择器并提供一秒的延迟)。
You can call
Or, more modernly:
Or, more modenly again:
Or, more modernly and more Cocoa-y:
All of these will halt the current thread. If your application has only one thread then this means it will halt your entire application. It will be unresponsive to any user interface events for the duration of the sleep.
The NSObject reference shows a method called performSelector:withObject:afterDelay:. This method performs the selector after the specified delay by scheduling it in the run loop. This means that the run loop continues to loop around and process events, fire timers, drain the autorelease pool, send more scheduled messages and so on and so on.
In this particular case, it is probably better to schedule the selector in the run loop (provide the selector that changes the image back and provide a delay of a second).