0

这是我的代码:

NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString *currentTime = [dateFormatter stringFromDate:currDate];

NSDate *now = [NSDate date];
int interval = 1*60; // one minute (minutes*60)
long int nowSeconds = (long int) [now timeIntervalSince1970];
int secondsLeft = interval - (nowSeconds % interval);

NSDate *nextIntervalDate =  [NSDate dateWithTimeIntervalSince1970:nowSeconds+secondsLeft];

NSString *nextTrigger = [dateFormatter stringFromDate:nextIntervalDate];

timeRemaining.text = [NSString stringWithFormat:@"%02d:%02d", secondsLeft/60, secondsLeft%60];

NSLog([NSString stringWithFormat:@"%@:%@", currentTime, nextTrigger]);

if ([currentTime isEqualToString:nextTrigger]) {

}

问题是,'if ([currentTime isEqualToString:nextTrigger])' 永远不相等。因为 nextTrigger 在它们相等之前更改为下一个时间段。这是NSLog:

2013-01-17 15:54:59.987 app[35987:c07] 15:54:59:15:55:00
2013-01-17 15:54:59.997 app[35987:c07] 15:54:59:15:55:00    
2013-01-17 15:55:00.007 app[35987:c07] 15:55:00:15:56:00   <----RIGHT HERE
2013-01-17 15:55:00.016 app[35987:c07] 15:55:00:15:56:00

我的代码的 nextTrigger 基本上是将当前时间按最近的分钟向上取整。此外,整个代码段每 0.1 秒重复一次 NSTimer。

我怎样才能解决这个问题?

4

2 回答 2

0

如果您有想要在下一整分钟过去时触发的代码,那么重复检查以查看所述时间是否已经过去是低效的。将该代码放入它自己的方法中,并创建一个 NSTimer 以在适当的时间触发它。

NSDate* date = [NSDate date] ;
NSCalendar* calendar = [NSCalendar currentCalendar] ;

NSDateComponents* secondsComponents = [calendar components:NSSecondCalendarUnit fromDate:date] ;
NSTimeInterval secondsUntilNextWholeMinute = 60 - secondsComponents.second ;
[NSTimer scheduledTimerWithTimeInterval:secondsUntilNextWholeMinute  target:self  selector:@selector(yourMethod)  userInfo:nil  repeats:NO ] ;
于 2013-01-17T21:42:34.443 回答
-1

我有一个类似的问题。我所做的是制作一个副本并通过它来检查它。(一件事是两者都有oldTrigger并且newTrigger已经声明)检查这个代码

NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString *currentTime = [dateFormatter stringFromDate:currDate];

NSDate *now = [NSDate date]; 
int interval = 1*60; // one minute (minutes*60)
long int nowSeconds = (long int) [now timeIntervalSince1970];
int secondsLeft = interval - (nowSeconds % interval);

NSDate *nextIntervalDate =  [NSDate dateWithTimeIntervalSince1970:nowSeconds+secondsLeft];
oldTrigger = nextTrigger;
nextTrigger = [dateFormatter stringFromDate:nextIntervalDate];

timeRemaining.text = [NSString stringWithFormat:@"%02d:%02d", secondsLeft/60, secondsLeft%60];

NSLog([NSString stringWithFormat:@"%@:%@", currentTime, nextTrigger]);

if ([currentTime isEqualToString:oldTrigger]) {

}
于 2013-01-17T21:44:05.900 回答