NSDate returns a negative NSTimeInterval

I have the following code:

- (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];
}

However, the value of elapsedTimeDisplayingPoints is perfectly accurate, except negative each time. Why does it return -3, -4, -5, etc?

Answers


If the receiver is earlier than anotherDate, the return value is negative. Which is the case with your example. You can use fabs() to get a positive value.


You get negative numbers because self.timeStartedDisplayingPoint is before [NSDate date].

You need:

NSDate *now = [NSDate date];
NSTimeInterval elapsedTimeDisplayingPoints = [now timeIntervalSinceDate:self.timeStartedDisplayingPoint];

Need Your Help

Optimization Techniques in Python

python

Recently i have developed a billing application for my company with Python/Django. For few months everything was fine but now i am observing that the performance is dropping because of more and more

Apache module - get request body

c++ linux apache

I am creating simple apache module to capture all HTTP traffic for real time processing by security software. My goal is to get headers and body from both request and response. So far I managed to ...