gpt4 book ai didi

ios - 45 分钟后计时器不会停止

转载 作者:行者123 更新时间:2023-11-29 03:33:14 25 4
gpt4 key购买 nike

我有一个 NSTimer,我希望它在 45 分钟后停止,但它不会停止。我做错了什么?

TIMER_COUNT = 45

HOURS_IN_HOURS = 60

HOURS_IN_DAY = 24

- (void)start
{
self.timerCountdown = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}

- (void)stop
{
[self.timerCountdown invalidate];
self.timerCountdown = nil;
}

- (void)updateCountdown
{
NSDate *currentDate = [NSDate date];
NSDate *finalTime = [currentDate dateByAddingTimeInterval:(TIMER_COUNT * HOURS_IN_HOUR)];

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *componentsHours = [calendar components:NSHourCalendarUnit fromDate:currentDate];
NSDateComponents *componentMinuts = [calendar components:NSMinuteCalendarUnit fromDate:currentDate];
NSDateComponents *componentSeconds = [calendar components:NSSecondCalendarUnit fromDate:currentDate];

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsDaysDiff = [gregorianCalendar components:NSDayCalendarUnit
fromDate:currentDate
toDate:finalTime
options:0];

NSLog(@"%20d Days, %02d Hours, %02d Minutes, %02d Seconds.", componentsDaysDiff.day, HOURS_IN_DAY - componentsHours.hour, HOURS_IN_HOUR - componentMinuts.minute, HOURS_IN_HOUR - componentSeconds.second);

if ([currentDate compare:finalTime] == NSOrderedSame)
{
NSLog(@"Done.");
[self stop];
}
}

提前致谢。

最佳答案

因为您的 currentDate 会在您的计时器每次计时时保持设置。每次 updateCountdown 方法运行时,[NSDate date] 都会将 currentDate 设置为当前时间。因此 finalTime 总是比 currentDate 早 45 分钟。您应该创建一个 startDate 属性并将其设置在 start 方法中:

- (void)start
{
self.timerCountdown = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
self.startDate = [NSDate date];
}

然后检查 updateCountdown 方法中的属性:

if ([self.startDate compare:finalTime] == NSOrderedSame)
{
NSLog(@"Done.");
[self stop];
}

或者,您可以使用一个整数来表示您期望的滴答数,然后每次计时器滴答时从该整数中减去一个。像这样:

- (void)start
{
self.timerCountdown = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats:YES];
self.countdown = TIMER_COUNT * HOURS_IN_HOUR;
}

- (void)updateCountdown
{
self.countdown--;

//your code

if (self.countdown == 0)
{
NSLog(@"Done.");
[self stop];
}
}

关于ios - 45 分钟后计时器不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19510565/

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