2011-11-03 72 views
0

我的計時器沒有得到重複,請幫助計時器沒有得到重複

這裏是代碼

timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(doAnimation:) userInfo:nil repeats:YES]; 
[timer fire]; 

方法

-(void)doAnimation:(id)Sender 
{ 
} 
+0

你是否在任何地方使計時器失效? – Krishnabhadra

+0

不,我只寫了上面的代碼 –

+0

只是使用[NSTimer scheduledTimerWithInterval:1.0 target:self selector:@selector(doAnimation :) userInfo:nil repeatats:YES],no fire。 –

回答

6

[timer fire]手動觸發計時器只有一次的,實際上並不是「啓動」定時器。從docs

您可以使用此方法觸發重複定時器而不中斷其常規發射計劃。如果計時器不重複,即使其計劃的起火日期尚未到達,它也會在發射後自動失效。

您需要add the timer在運行循環之前,將開始射擊,並重復:

您必須將新的計時器添加到運行循環,使用addTimer:forMode :.然後,秒鐘過後,計時器觸發,發送消息aSelector作爲目標。 (如果計時器被配置爲重複,沒有必要隨後計時器重新添加到運行循環。)

更簡單的方法是做這樣的事情:

timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doAnimation:) userInfo:nil repeats:YES]; 

和:

-(void)doAnimation:(NSTimer*)timer 
{ 
} 

這個automatically schedules該計時器並將其添加到運行循環。如果您沒有這樣做,因爲您已將目標設置爲self,您必須確保方法doAnimation在相同的類中定義。

NSTimer Class Reference

+0

然後如何啓動定時器任何其他方法然後運行循環 –

+0

我已經添加了新的代碼來做到這一點在我的答案 – Adam

+0

謝謝它的工作 –

3

使用timerWithTimeInterval需要你把它連接到一個運行循環。嘗試使用

timer = [NSTimer scheduledTimerWithTimeInterval:1 target self selector:@selector(doAnimation:) userInfo:nil repeats:YES]; 

改變你的doAnimation方法如下:

-(void)doAnimation:(NSTimer *)timer{ 
     // do Something 
} 

P.S你爲什麼要告訴它立即火?我不認爲這是必要的。

0

我的猜測,給出的細節,就是要添加的計時器的運行循環上退出1秒結束前一個線程。

示例:您在輔助線程上創建計時器,計時器在輔助線程退出時被銷燬。

當一個線程死亡,其運行循環死了,當它的運行循環終止,其定時器無效。

如果是這種情況,一個簡單的方法是將其添加到主運行循環中。

在某些情況下,您會(當然)希望定時器運行在特定的運行循環或線程上,但是這種誤解在過去給人們帶來了類似的問題。