簡體   English   中英

NSTimer-if語句在計時器內不起作用-CountDown計時器

[英]NSTimer - if statement not working within timer - CountDown Timer

我正在開發一個遞減計時器,當計數小於0時,如果無法通過if語句來停止計時器,我將遇到麻煩。解決此問題的任何指導將不勝感激。 在此先感謝您的幫助..

   -(void) startCountdown{
time = 90;
//NSLog[@"Time Left %d Seconds", time];
//This timer will call the function updateInterface every 1 second

   myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateInterface:) userInfo:nil repeats:YES];
}



-(void) updateInterface:(NSTimer*)theTimer{
if(time >= 0){
    time --;
    CountDownText.text = [NSString stringWithFormat:@"%d", time];
    NSLog(@"Time Left %d Seconds", time);
}
else{
    CountDownText.text =@"Times Up!";
    NSLog(@"Times Up!");
    // Timer gets killed and no longer calls updateInterface
    [myTimer invalidate];
}
}

我測試了您的代碼,它運行良好,並且計時器在-1處停止。 因此,我最好的猜測是time可能被聲明為無符號值,因此它永遠不會小於零。

倒數直到達到-1(而不是0)似乎不會停止,因為您要檢查大於等於 0的值,然后遞減(然后顯示)。

首先減少,然后檢查時間是否大於零:

-(void) updateInterface:(NSTimer*)theTimer{
    time --;
    if(time > 0){
        CountDownText.text = ...

或檢查時間是否大於1:

-(void) updateInterface:(NSTimer*)theTimer{
    if(time > 1){
        time --;
        CountDownText.text = ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM