2011-11-23 267 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保留该对象。 –