2012-06-05 34 views
0

我正在尝试建立一个倒计时,显示秒数。使用NSDateComponents准确计时

以下示例设置为10秒,但输出为8秒。

NSDate *currentDate = [NSDate date]; 
NSDate *finishDate = [NSDate dateWithTimeInterval:10 sinceDate:currentDate]; 

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

NSDateComponents *components = [calendar components:NSSecondCalendarUnit|NSMinuteCalendarUnit|NSHourCalendarUnit | NSDayCalendarUnit| NSMonthCalendarUnit | NSYearCalendarUnit 
              fromDate:currentDate 
              toDate:finishDate 
              options:0]; 
NSInteger hour_ = [components hour]; 
NSInteger minute_ = [components minute]; 
NSInteger second_ = [components second]; 

登录

currentDate = 2012-06-05 03:13:10 +0000 
finishDate_ = 2012-06-05 03:13:19 +0000 
second_ = 8 
+0

请注意,这不是真正的“时间”,但更多的日期计算...... – lnafziger

回答

0

好吧,我只是复制和粘贴代码。 我添加了这些线的底部:

NSLog(@"%@", currentDate); 
NSLog(@"%@", finishDate); 
NSLog(@"%d, %d, %d", hour_, minute_, second_); 

它的工作完美,使用上运行iOS 5.1在iPad模拟器的Xcode 4.3.2:

2012-06-05 00:19:34.341 Testing App[59813:fb03] 2012-06-05 04:19:34 +0000 
2012-06-05 00:19:34.342 Testing App[59813:fb03] 2012-06-05 04:19:44 +0000 
2012-06-05 00:19:34.343 Testing App[59813:fb03] 0, 0, 10 

您是否使用不同的版本?

+0

我正在使用这些版本。当前和结束日期呢? – daidai

+0

现实情况是,这段代码是实际发生的简化版本。我复制了上面的代码并得到了与您相同的结果,因此必须与执行导致偏移量的其他任务所花费的时间有关。 – daidai

+0

那么,因为您将时间添加到起始值,所以花费额外的时间进行计算应该没有关系。这是简单的数学.... – lnafziger