Here I have a code that sets fireDate of an NSTimer object.
-(void)TimerFired:(NSTimer*)timer{
long startTime=random()%1500+500;
[timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:startTime/1000.0]];
[controller startCarFromLane:self];
}
In the above code when I write :startTime/1000.0 I get the timer fired after fairly enough amount of time. But if I change it to :startTime/1000 (without .0) timer’s next fireDate is different from the case above,the timer fires more frequently . I know that dateWithTimeIntervalSinceNow method expects an NSTimeInterval which is a typedef of double. But can’t I write 10.0 as just 10? How can the .0 have an impact on the value?
When you simply write 1000, the compiler implies an integer type. Thus, when dividing two integers (startTime is a long and 1000 is probably an int), it would be integer division, resulting in the floor of the accurate (exact) ration. E. g., 2500 / 1000 will be 2. However, when you write 1000 as 1000.0, the compiler emits a float. An integer divided by a float results in a float, so 2500 / 1000.0 will be 2.5, as expected. Basically that’s why you get shorter intervals when simply using an integer. (In other words, it’s the fact that integer division throws away the modulo divided by the divisor).