Objective C相当于javascripts setTimeout?

时间:2009-09-16 09:19:32

标签: iphone objective-c cocoa-touch timer

我想知道在CocoaTouch ObjectiveC中是否有30秒或每30秒举一次事件的解决方案。

4 个答案:

答案 0 :(得分:42)

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
});

修改 一些提供语法糖和取消执行能力的项目(clearTimeout):

答案 1 :(得分:32)

有很多选择。

最快使用的是NSObject

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay

(还有一些其他变化很小。)

如果您想要更多控制权或者能够说每三十秒发送一条消息,您可能需要NSTimer

答案 2 :(得分:12)

看一下NSTimer课程:

NSTimer *timer;
...
timer = [[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(thisMethodGetsFiredOnceEveryThirtySeconds:) userInfo:nil repeats:YES] retain];
[timer fire];

其他地方你有处理事件的实际方法:

- (void) thisMethodGetsFiredOnceEveryThirtySeconds:(id)sender {
   NSLog(@"fired!");
}

答案 3 :(得分:3)

+[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]

Documentation

您可能还想查看其他NSTimer方法