gpt4 book ai didi

iphone - 为什么我的时间间隔会得到负值?

转载 作者:行者123 更新时间:2023-11-28 18:11:17 25 4
gpt4 key购买 nike

我不知道发生了什么。我正在尝试制作一个通过比较日期来工作的计时器。当我启动计时器时,有时它工作然后随机停止,有时它只返回 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);
}

最佳答案

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

关于iphone - 为什么我的时间间隔会得到负值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18176056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com