我想知道在CocoaTouch ObjectiveC中是否有30秒或每30秒举一次事件的解决方案。
答案 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:]
您可能还想查看其他NSTimer
方法