簡體   English   中英

倒數計時器不會在0處停止

[英]Countdown timer doesn't stop at 0

我有一個計時器,如果計時器在前台,則可以很好地工作。 它完美地遞減並在0處停止。但是,當我點擊homebutton進入主屏幕,然后等待本地通知彈出,然后我點擊通知時,時間間隔變為42億(上限用於無符號的long int)。 基本上,它不會在0處停止。我不確定如何解決此問題。 我嘗試將其設置為常規NSInteger,並檢查間隔是否低於0,但得到的結果相同。

-(IBAction)startTimer:(id)sender{
    if (!timer) {
        [startButton setTitle:@"Start" forState:UIControlStateNormal];
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
       date = [NSDate date];
    } else {
        [startButton setTitle:@"Stop" forState:UIControlStateNormal];
        anotherTimeInterval = testTask.timeInterval;
        [timer invalidate];
        timer = nil;
    }

}

-(void)timerAction:(NSTimer *)t
{
    NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:date];
    if (testTask.timeInterval > 0){
        NSError *error;
        if (![self.context save:&error]) {
            NSLog(@"couldn't save: %@", [error localizedDescription]);
        }
        NSUInteger seconds = (NSUInteger)round(anotherTimeInterval-interval);
        NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u",
                            seconds / 3600, (seconds / 60) % 60, seconds % 60];
        testTask.timeInterval = seconds;
        timerLabel.text = string;
        NSLog(@"%@", string);
    } else {
        NSLog(@"timer ended");
        [self.timer invalidate];
        self.timer = nil;
        [self timerExpired];
    }
}

-(void)applicationWillResignActive:(UIApplication *)application{
    if (timer){
        UILocalNotification* localNotification = [[UILocalNotification alloc] init];
        localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:testTask.timeInterval];
        localNotification.alertBody = @"Time is up";
        localNotification.alertAction = @"Ok";
        localNotification.timeZone = [NSTimeZone defaultTimeZone];
        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    }
}

您在stringWithFormat:使用的%02u將值解析為一個無符號的int。

另外,我認為這是您的問題,您正在if語句中檢查testTask.timeInterval,但是從方法開始時獲得的interval變量中獲取秒數。 因此,您始終在檢查先前的值,這意味着始終落后一秒。

編輯:您可以這樣做:

NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:date];
if (anotherTimeInterval-interval > 0){
    ...
}

這樣,您將檢查值而不是舊值。

希望這可以幫助

暫無
暫無

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

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