xcode 我应该能够使用 NSTimer 延迟 2 秒。怎么做?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3711831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I should able to delay 2 seconds using NSTimer. How to do it?
提问by Linux world
I want to produce a delay of 2 seconds using NSTimer how to initialize timer in program?
我想使用 NSTimer 产生 2 秒的延迟如何在程序中初始化计时器?
回答by davydotcom
Multiple options here.
这里有多种选择。
If you just want a delay of 2 seconds you could use the sleep() function
如果你只想延迟 2 秒,你可以使用 sleep() 函数
#include<unistd.h>
...
sleep(2);
Or you may be able to use NSTimer like so
或者你可以像这样使用 NSTimer
[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
}
回答by Lee Armstrong
Here you go...
干得好...
[NSTimer scheduledTimerWithTimeInterval:2
target:self
selector:@selector(action)
userInfo:nil
repeats:NO];
回答by T?nu Samuel
Simple answer: [NSThread sleepForTimeInterval:10.0];
简单回答:[NSThread sleepForTimeInterval:10.0];
回答by hotpaw2
Note that you should not really be thinking about delays in an event driven UI/OS. You should thinking about tasks you want to do now, and tasks you want to do later, and code these subtasks and schedule them appropriately. e.g. instead of:
请注意,您不应该真正考虑事件驱动的 UI/OS 中的延迟。你应该考虑你现在想要做的任务,以及你以后想要做的任务,并对这些子任务进行编码并适当地安排它们。例如,而不是:
// code that will block the UI when done in the main thread
- (void) methodC {
doA();
delay(2);
doB();
}
you might want to have code that looks more like:
您可能希望代码看起来更像:
- (void) methodA {
doA();
return; // back to the run loop where other useful stuff might happen
}
- (void) methodB {
doB();
}
and you can then schedule methodB with an NSTimer at the end of methodA, an NSTimer started by whatever called methodA, or, the best option, by the asynchronous completion routine of something started by methodA.
然后,您可以在 methodA 的末尾使用 NSTimer 调度 methodB,由任何调用的 methodA 启动的 NSTimer,或者最好的选择,由 methodA 启动的某事的异步完成例程。