[英]Negative NSTimeInterval in NSDate's dateWithTimeIntervalSinceNow:
[英]NSDate returns a negative NSTimeInterval
我有以下代碼:
- (void)pointsStartedDisplaying {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dispatch_async(dispatch_get_main_queue(), ^{
self.timeStartedDisplayingPoint = [NSDate date];
self.stopButton.enabled = YES;
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateElapsedTime:) userInfo:nil repeats:YES];
});
});
}
- (void)updateElapsedTime:(NSTimer *)timer {
NSTimeInterval elapsedTimeDisplayingPoints = [self.timeStartedDisplayingPoint timeIntervalSinceDate:[NSDate date]];
self.elapsedTimeValueLabel.text = [NSString stringWithFormat:@"%f seconds", elapsedTimeDisplayingPoints];
}
但是, elapsedTimeDisplayingPoints
的值是完全准確的,除了每次都是負值。 為什么返回-3, -4, -5,
等?
如果接收者早於anotherDate,則返回值為負 。 您的示例就是這種情況。 您可以使用fabs()獲得正值。
您會得到負數,因為self.timeStartedDisplayingPoint
在[NSDate date]
之前。
你需要:
NSDate *now = [NSDate date];
NSTimeInterval elapsedTimeDisplayingPoints = [now timeIntervalSinceDate:self.timeStartedDisplayingPoint];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.