我想知道是否有一个解决方案,以30秒或在CocoaTouch的ObjectiveC每30秒一次后引发事件。
Answer 1:
有许多的选择。
用最快的是在NSObject
:
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
(有几个人有轻微的变化。)
如果你想要更多的控制,或者可以说发这条短信每三十秒,你可能需要NSTimer
。
Answer 2:
该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)项目:
- https://github.com/Spaceman-Labs/Dispatch-Cancel
- https://gist.github.com/zwaldowski/955123
Answer 3:
看看的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!");
}
Answer 4:
+[NSTimer scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:]
文档
你可能也想看看其他NSTimer
方法
文章来源: Objective C equivalent to javascripts setTimeout?