开发者

Is there a way to write a NSTimer so it just pauses the program for a second?

Trying to change a button pic, wait a second, then change back. Not having much luck trying to get that to wo开发者_如何学Pythonrk, 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?


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

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜