Calculating 'timeIntervalSinceNow' with negative value (CLLocation example)?
I don't understand this example from the doc: the method timeIntervalSinceNow
should show a positive value, but how can we achieve "5" as stated in the code? (I think this is either more than 0, or -10, -20, -30, etc ... but how can we get a positive value like 5?):
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
// test the age of the location measurement to determine if the measurement is cached
// in most cases you will not want to rely on cached measurements
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0) return;
thanks for the help
source to share
If the result of the call is timeIntervalSinceNow
negative (meaning that the timestamp is in the past (which in this case will always be)), it will be converted to a positive number. -2.5
would +2.5
, for example (and vice versa).
Then you check the value of the inverted sign to see if it's greater than 5.0 - in this case, that means the timestamp is more than five seconds ago. If so, you are not doing anything with the location data because it is too old to be useful.
Personally, I would write this without inverting the sign, using a negative number in the test:
if( [[newLocation timestamp] timeIntervalSinceNow] < -5.0 ) return;
source to share
This is what the NSDate documentation has to say about timeIntervalSinceNow:
The interval between the receiver and the current date and time. If the receiver is earlier than the current date and time, the return value is negative.
In this case, the time stamp was recorded in the past and will always be earlier than "now". If, on the other hand, you use timeIntervalSince1970, the result is positive.
source to share