我正在创建一个简单的乒乓球游戏..
现在我想设置一个计时器,它会在我松开后停止并将值保存到高分可能,但即使我设法设置计时器并设置他,它似乎不想停止.
我正在使用本教程实现它:
http://www.apptite.be/tutorial_ios_stopwatch.php
现在我的代码看起来像这样:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (StavHry == StavHryPozastaven) {
TapToBegin.hidden = YES;
StavHry = StavHryAktivni;
} else if (StavHry == StavHryAktivni) {
[self touchesMoved:touches withEvent:event];
}
startDate = [NSDate date];
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0 target:self selector:@selector(updateTimer)userInfo:nil repeats:YES];
}
- (void)updateTimer
{
static NSInteger counter = 0;
StopWatchLabel.text = [NSString stringWithFormat:@"Counter: %i", counter++];
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
StopWatchLabel.text = timeString;
}
当我点击TapToBegin标签时,我设置了计时器..
但是当我松开或赢得计时器时,即使我在设置新游戏之前在功能中使用了无效,我也会继续运行..(当我开始新游戏时它会重置)
-(void)reset:(BOOL) novahra { //funkce reset
self.StavHry = StavHryPozastaven;
mic.center = self.view.center;
if(novahra) {
if(skore_hrac_hodnota < skore_pc_hodnota){
TapToBegin.text = @"Protivnik Vyhrál, smůla!";
[stopWatchTimer invalidate];
} else {
TapToBegin.text = @"Vyhráls! Gratulujem!";
[stopWatchTimer invalidate];
}
skore_hrac_hodnota = 0;
skore_pc_hodnota = 0;
} else {
self.StavHry = StavHryAktivni;
//TapToBegin.text = @"Pokračuj!";
}
skore_hrac.text = [NSString stringWithFormat:@"%d", skore_hrac_hodnota];
skore_pc.text = [NSString stringWithFormat:@"%d", skore_pc_hodnota];
}
我知道教程显示更多的代码行为它的停止动作,但我尝试了更多选项我给它所有的一切,但我认为这是唯一停止计时器的行,所以它应该工作.但事实并非如此.
请帮助,我星期一到期完成这个,所以我吓坏了一点.
最佳答案 如果touchesBegan:被多次调用并且重置:在两者之间不被调用会发生什么?如果它可能发生,你可能会泄漏一个计时器,它将继续调用你的updateTimer方法.
如果您发布的代码作为计时器方法应该采取参数,我有点惊讶.这是将您的计时器选择器更改为@selector(updateTimer :),然后将方法更改为 – (void)updateTimer:(NSTimer *)计时器.