I have a problem with NSTimer. I start and repeat it every 100ms and I have a counter to check if i runed 10s. The problem is it stoped in near 1 minute, not in 10s. Here is my code
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(checkTimer) userInfo:nil repeats:YES];
-(void)checkTimer
{
timerCount += 1;
if(timerCount == 1)
{
NSLog(@"start");
}
if(timerCount == 103)
{
NSLog(@"i got it");
}
}
here is the log:
2012-11-19 08:57:42.063 Karagram[11708:540b] start
[Switching to process 8707 thread 0x2203]
2012-11-19 08:58:39.514 Karagram[11708:540b] i got it
I don't understand why it wrong. Somebody can tell me why? Thanks.
NSTimers aren't guaranteed to be accurate to within more than 100 ms or so. The NSTimer documentation says:
By having it fire every 100ms you're compounding the error, because if it's off 50 ms every 100ms, by the time 10s has passed it could be quite far from what you expect.
If you're wanting to take some action after 10s, why not just set the timer to fire after 10s?
Also, are you doing your streaming on the main thread? NSTimers work on the main runloop, so if you're blocking the main thread, timers aren't going to fire until it's unblocked.