我想使用 NSTimer 产生 2 秒的延迟,如何在程序中初始化计时器?
14532 次
4 回答
12
Multiple options here.
If you just want a delay of 2 seconds you could use the sleep() function
#include<unistd.h>
...
sleep(2);
Or you may be able to use NSTimer like so
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(fireMethod) userInfo:nil repeats:NO];
And in your class you would have a method defined as
-(void)fireMethod
{
//Do stuff
}
于 2010-09-14T18:36:12.877 回答
4
Here you go...
[NSTimer scheduledTimerWithTimeInterval:2
target:self
selector:@selector(action)
userInfo:nil
repeats:NO];
于 2010-09-14T18:35:48.287 回答
1
简单的答案:[NSThread sleepForTimeInterval:10.0];
于 2016-03-10T05:10:34.530 回答
-1
请注意,您不应该真正考虑事件驱动的 UI/OS 中的延迟。您应该考虑现在要执行的任务以及以后要执行的任务,并对这些子任务进行编码并适当地安排它们。例如,而不是:
// code that will block the UI when done in the main thread
- (void) methodC {
doA();
delay(2);
doB();
}
您可能希望代码看起来更像:
- (void) methodA {
doA();
return; // back to the run loop where other useful stuff might happen
}
- (void) methodB {
doB();
}
然后你可以在methodA的末尾使用NSTimer来调度methodB,一个由methodA启动的NSTimer,或者最好的选择,由methodA启动的异步完成例程。
于 2010-09-14T21:08:12.630 回答