developerWab 2013-08-14 08:07 采纳率: 0%
浏览 1072

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);
}
  • 写回答

1条回答

  • ChatGPTᴼᴾᴱᴺᴬᴵ 2023-01-12 13:41
    关注

    这段代码实现了一个计时器,当用户按下 "Start" 按钮时,会开始一个计时器,每秒执行一次 "timerAction" 方法。在 "timerAction" 方法中,使用 "date" 变量保存了当前时间加上 "testTask.timeInterval" 的时间值,然后计算 "date" 与当前时间的时间差 "updatedTimeInterval"。如果 "updatedTimeInterval" 大于 0,则说明计时结束,运行 "timerExpired" 方法并停止计时器,否则将 "updatedTimeInterval" 的值保存到 "testTask.timeInterval" 中并输出。


    那么为什么结果随机停止呢?可能是在运行 "timerExpired" 方法和停止计时器之前,计时器仍在运行,导致"testTask.timeInterval"有可能为负数。或者说,"timerExpired" 方法不能正确处理过时事件,导致计时器无法正常工作。


    我建议在timerAction中加入一个对timer的判断,如果在调用timerExpired后,这个timer还存在,那么应该销毁这个timer。比如这样

    if (self.timer)
    {
        [self timerExpired];
        [self.timer invalidate];
        self.timer = nil;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形