2012-05-26 13 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

タイマーをスケジュールして、イベントを同じコード行ですべて発生させることはできません。だからあなたは2行のコードでそれをしなければならない。

まず、すぐにタイマーの「火」と呼ぶ、その後、タイマーをスケジュールします。その後、火が呼び出されると、それだけで走ったので、あなたのタイマーが起動するまで待機する時間間隔はリセットされます

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

関連する問題