2011-10-25 41 views
0

我希望我的NSTimer到每次運行時加快:每次降低的NSTimer間隔運行

-(void)runtimer { 
    int delay = delay - 1; 
    [NSTimer scheduledTimerWithTimeInterval:(delay) 
            target:self 
            selector:@selector(timerTriggered:) 
            userInfo:nil 
            repeats:YES]; 

} 

但是,這是行不通的。我怎樣才能讓延遲變得越來越小?

回答

0

你必須在類的接口或靜態變量中聲明延遲。

此外,每次創建一個新的計時器,而不是重複。

int delay = INITIAL_DELAY; 

-(void)runtimer{ 
    [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)(delay--) target:self selector:@selector(runTimer:) userInfo:nil repeats:NO]; 
} 
+0

定時器確實是每次都重新創建,並且給定一個叫做'timerTriggered:'的不同方法來觸發。 –

1

每次運行此方法時,都會創建一個名爲delay的新變量,然後嘗試將其設置爲自己減1.這是未定義的行爲(該變量未初始化爲任何內容),並且可能會導致垃圾值爲delay。*

您需要將延遲存儲在實例變量中。

- (void) runTimer { 
    // You are declaring a new int called |delay| here. 
    int delay = delay - 1; 
    // This is not the same |delay| that you have declared in your header. 
    // To access that variable, use: 
    delay = delay - 1; 

* A sinus infestation by evil-aligned supernatural beings也是一種可能性。

+0

我其實只是因爲我忘了說這個,所以我沒有發佈。所以,即使我在頭後它仍然無法工作... – JDanek

+1

您發佈的片段有一個局部變量陰影伊娃然後。 –

0

創建定時器後,您無法更改定時器的啓動間隔。如果你想要一個不同的時間間隔,你必須使先前的定時器無效(因此你應該保留對它的引用),然後用不同的時間間隔創建一個新的定時器。

+0

此代碼不會嘗試更改間隔;實際上,每次都會創建一個新的計時器。 –

+1

...但創建定時器的代碼在'YES'中傳遞'repeats:'參數,這意味着在無限循環結束時會有很多定時器運行。 –

+0

@Rob:我假設(也許是錯誤的)他們在'timerTriggered:'中失效。 –

3

needed this myself並寫了一個組件CPAccelerationTimer (Github)

[[CPAccelerationTimer accelerationTimerWithTicks:20 
    totalDuration:10.0 
    controlPoint1:CGPointMake(0.5, 0.0) // ease in 
    controlPoint2:CGPointMake(1.0, 1.0) 
    atEachTickDo:^(NSUInteger tickIndex) { 
     [self timerTriggered:nil]; 
    } completion:^{ 
     [self timerTriggered:nil]; 
    }] 
run]; 

這就要求-timerTriggered: 20倍,散佈在10秒,以不斷減小的延遲(如由給定的貝塞爾曲線指定)。