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 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题