2012-05-26 103 views
32

我需要在我的应用程序启动时调用方法,然后每5秒调用一次相同的方法。如何立即触发NSTimer?

我的代码非常简单:

// Call the method right away 
[self updatestuff:nil] 

// Set up a timer so the method is called every 5 seconds 
timer = [NSTimer scheduledTimerWithTimeInterval: 5 
              target: self 
             selector: @selector(updatestuff:)  
             userInfo: nil 
             repeats: YES]; 

是否有定时器所以它的触发马上,然后每隔5秒的选项?

回答

65

NSTimer-fire[timer fire];是你在找什么。

这将触发/立即调用计时器解散时间延迟。

13

您不能安排计时器,并立即在同一行代码中激发事件。所以你必须在两行代码中完成。

首先,安排计时器,然后立即打电话给“火”在你的计时器:

timer = [NSTimer scheduledTimerWithTimeInterval: 5 
             target: self 
            selector: @selector(updatestuff:)  
            userInfo: nil 
            repeats: YES]; 
[timer fire]; 

当火被调用时,你的计时器等待开火的时间间隔将重置,因为它只是跑了,然后将以指定的时间间隔继续运行 - 在这种情况下,每5秒钟一次。

3

您可以初始化计时器,并在同一行火了:

[(checkStatusTimer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(checkStatusTimerTick:) userInfo:nil repeats:YES]) fire]; 
+1

很不错的语法! – loretoparisi