有没有办法编写一个 NSTimer 以便它只是暂停程序一秒钟?

发布于 2024-09-02 06:05:56 字数 84 浏览 0 评论 0原文

尝试更改按钮图片,请稍等,然后再更改回来。没有太多运气试图让它工作,所以有没有办法只暂停程序一秒钟,而不让计时器实际执行任何东西,并且程序不继续执行代码?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

成熟的代价 2024-09-09 06:05:56

尝试将更改代码放入方法中,然后从更改方法中调用:

[self performSelector:@selector(changeBack:) withObject:nil afterDelay:1.0];

Try putting your change back code in a method, and call from your change method:

[self performSelector:@selector(changeBack:) withObject:nil afterDelay:1.0];
迷迭香的记忆 2024-09-09 06:05:56

你可以调用

// sleep first appeared in Version 7 UNIX, 1979
sleep(1);

Or,更现代的:

// usleep appeared in 4.3 BSD, released 1986
usleep(1000000);

或者,更现代的:

// nanosleep can be found in POSIX.1b, published 1993
struct timespec ts;
ts.tv_sec = 1;
nanosleep(&ts, NULL);

或者,更现代的、更可可的:

// +sleepForTimeInterval first appeared in Mac OS X 10.5, 2007
[NSThread sleepForTimeInterval:1.0];

所有这些都会停止当前线程。如果您的应用程序只有一个线程,那么这意味着它将停止您的整个应用程序。在睡眠期间它将不会响应任何用户界面事件。

NSObject 参考显示了一个名为 performSelector:withObject:afterDelay:。此方法通过在运行循环中调度它来在指定的延迟后执行选择器。这意味着运行循环继续循环并处理事件、触发计时器、耗尽自动释放池、发送更多预定消息等等。

在这种特殊情况下,最好在运行循环中安排选择器(提供将图像更改回来的选择器并提供一秒的延迟)。

You can call

// sleep first appeared in Version 7 UNIX, 1979
sleep(1);

Or, more modernly:

// usleep appeared in 4.3 BSD, released 1986
usleep(1000000);

Or, more modenly again:

// nanosleep can be found in POSIX.1b, published 1993
struct timespec ts;
ts.tv_sec = 1;
nanosleep(&ts, NULL);

Or, more modernly and more Cocoa-y:

// +sleepForTimeInterval first appeared in Mac OS X 10.5, 2007
[NSThread sleepForTimeInterval:1.0];

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文