【问题标题】:why am i getting negative values for my timeinterval?为什么我的时间间隔得到负值?
【发布时间】:2013-08-11 19:55:08
【问题描述】:

我不知道发生了什么。我正在尝试制作一个通过比较日期来工作的计时器。当我启动计时器时,有时它会工作然后随机停止,有时它只是返回 timeInterval 的值。它似乎只有在时间间隔为负时才能正常工作。这是我的方法:

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

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

【问题讨论】:

    标签: iphone ios objective-c nstimer countdown


    【解决方案1】:

    您正在从较早的 date 中减去较晚的日期 currentDate。我告诉过你反过来做:[[NSDate date] timeIntervalSinceDate:date]

    【讨论】:

    • 刚刚改成这样。现在,当我按下开始时,计时器立即显示 1193046 小时...
    • 如果date是你用来存储定时器开始时间的变量,它应该设置为当前日期——date = [NSDate date];,而不是dateWithTimeIntervalSinceNow:
    【解决方案2】:

    timeIntervalSinceNow 不被称为 timeIntervalUntilNow 是有原因的...

    也称为:如果所讨论的日期早于当前日期/时间,则从现在开始经过的时间为负数。如果日期晚于当前日期,那将是肯定的。 (只是一点逻辑和/或英语语义:))

       Earlier date      Current date
            ^                  ^
            +------------------+
                  since now: (earlier date) - (current date)... that's < 0
    

    【讨论】:

    • 刚刚改成这样。现在当我按开始时,计时器立即显示 1193046 小时
    • @EvilAegis 改变了...什么变成什么?
    • NSTimeInterval updatedTimeInterval = [日期 timeIntervalSinceDate:currentDate] 到 NSTimeInterval updatedTimeInterval = [currentDate timeIntervalSinceDate:date]。我基本上换了日期
    • @EvilAegis 好吧。在这种情况下,我建议您省略 NSDate *date = [NSDate dateWithTimeIntervalSinceNow:] 等部分。只需将间隔存储为NSTimeInterval 实例变量,并在计算剩余时间时使用它。
    • 用它来计算剩余时间是什么意思?这与仅仅减少时间间隔有什么不同:O?
    猜你喜欢
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 2022-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多