objective-c Objective C 相当于 javascripts setTimeout?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1431895/
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
Objective C equivalent to javascripts setTimeout?
提问by jantimon
I was wondering whether there is a solution to raise an event once after 30 seconds or every 30 seconds in CocoaTouch ObjectiveC.
我想知道是否有解决方案可以在 CocoaTouch ObjectiveC 中在 30 秒或每 30 秒后引发一次事件。
回答by Blago
The performSelector: family has its limitations. Here is the closest setTimeout equivalent:
performSelector: 系列有其局限性。这是最接近的 setTimeout 等效项:
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 0.5);
dispatch_after(delay, dispatch_get_main_queue(), ^(void){
// do work in the UI thread here
});
EDIT:A couple of projects that provide syntactic sugar and the ability to cancel execution (clearTimeout):
编辑:几个提供语法糖和取消执行能力的项目(clearTimeout):
回答by Stephen Darlington
There are a number of options.
有多种选择。
The quickest to use is in NSObject:
最快的使用是在NSObject:
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
(There are a few others with slight variations.)
(还有其他一些略有变化。)
If you want more control or to be able to say send this message every thirty seconds you probably need NSTimer.
如果您想要更多控制或能够说每 30 秒发送一次此消息,您可能需要NSTimer。
回答by Alex Reynolds
Take a look at the NSTimerclass:
看一下NSTimer类:
NSTimer *timer;
...
timer = [[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(thisMethodGetsFiredOnceEveryThirtySeconds:) userInfo:nil repeats:YES] retain];
[timer fire];
Somewhere else you have the actual method that handles the event:
在其他地方,您有处理事件的实际方法:
- (void) thisMethodGetsFiredOnceEveryThirtySeconds:(id)sender {
NSLog(@"fired!");
}
回答by Joost
+[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]
You may also want to look at the other NSTimermethods
您可能还想查看其他NSTimer方法

