Objective C相当于javascripts setTimeout?

jan*_*mon 26 iphone cocoa-touch timer objective-c

我想知道是否有一个解决方案在CocoaTouch ObjectiveC中在30秒或每30秒后发生一次事件.

Bla*_*ago 44

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
});
Run Code Online (Sandbox Code Playgroud)

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


Ste*_*ton 32

有很多选择.

最快的用途是NSObject:

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
Run Code Online (Sandbox Code Playgroud)

(还有一些其他略有变化.)

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


Ale*_*lds 13

看看NSTimer课程:

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

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

- (void) thisMethodGetsFiredOnceEveryThirtySeconds:(id)sender {
   NSLog(@"fired!");
}
Run Code Online (Sandbox Code Playgroud)