簡體   English   中英

iOS Pong開發,計時器不會停止

[英]iOS pong development, timer won't stop

我正在創建一個簡單的乒乓球游戲..現在我想設置一個計時器,該計時器在松動並可能將值保存為高分后將停止,但是即使我設法設置了計時器並將其設置為打開,不想停止。

我正在使用本教程實施它: 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:並在兩次調用之間未reset:會發生什么? 如果可能發生,那么您可能泄漏了一個計時器,該計時器將繼續調用您的updateTimer方法。

如果您發布的代碼可以作為timer方法的參數工作,我會感到有些驚訝。 那就是將您的計時器選擇器更改為@selector(updateTimer:) ,然后更改為- (void)updateTimer:(NSTimer *)timer

暫無
暫無

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

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