2011-11-23 256 views
0

我有問題如何停止計時器。雖然我不太瞭解它的工作原理。請幫幫我。如何重置計時器?

我有一個智商應用程序,假設有10個問題,每個問題都不能在4秒內回答。

- (void) requestForItem 
{ 
    TrainEnglishAppDelegate *delegate = (TrainEnglishAppDelegate*)[UIApplication sharedApplication].delegate; 
    NSDictionary *item = [delegate.allQuestions objectAtIndex:z]; 


    questionLabel.text = [item objectForKey:kQuestion]; 
    questionNumber.text = [NSString stringWithFormat:@"Question %d/%d",no,totalNo]; 
    NSArray *answers = [item objectForKey:kAnswers]; 
    aLabel.text = [answers objectAtIndex:0]; 
    bLabel.text = [answers objectAtIndex:1]; 
    cLabel.text = [answers objectAtIndex:2]; 
    [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(pressToNextQuestion:) userInfo:nil repeats:NO]; 
} 

此操作直到出現跳過問題按鈕。用戶按下一個按鈕,跳過問題,但該問題中的計時器仍在計時。那麼當我在另一個問題上時,我的時間就減少了。按下跳轉時如何重置計時器?請幫幫我。非常感謝

回答

3

定時器失效可以通過以下方式

 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(pressToNextQuestion:) userInfo:nil repeats:NO]; 

     [timer invalidate]; //To stop the timer 

進行,以便把你的計時器在一個變量,並停止它,只需用第二線,無論你想停止它。

0

您可以將pulseTimer聲明爲類變量,以便稍後訪問它以使計時器失效。在問題選擇的開始和結束以及給出答案時進行這些調用,您可以獲得所需的功能。

-(void)createTimer 
    { 
      self.pulseTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(pressToNextQuestion) userInfo:nil repeats:NO]; 
      [self.pulseTimer fire]; 
    } 

//這將停止計時器,從這裏開始,您可以重新啓動下一個問題。

-(void)deactivateTimer { 
    [pulseTimer invalidate]; 
} 
+0

不要釋放定時器,它是一個autorelease對象,而且你正在過度釋放它。只有alloc,new,copy和mutableCopy對象應該被釋放。 – rckoenes

+1

感謝您的糾正,我編輯了我的答案。 pulseTimer保留該對象。 –