in my application,I have implemented NSTimer to count time.I have swipe detection and when
the user swipes on the screen,animation runs continuously.my question is when I swipe
on the screen(left/right continuously) NSTimer slows down.
can anybody tell me how to solve this problem?
//code
gameTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/100
target:self
selector:@selector(updateGameTimer)
userInfo:nil
repeats:YES];
-(void)updateGameTimer
{
counter++;
tick++;
if(tick==100){
tick = 0;
seconds += 1;
}
if(counter==100){
counter = 0;
}
timerLabel.text = [NSString stringWithFormat:@"%i.%02d",seconds,counter];
}
//swipe detection
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
[super touchesMoved:touches withEvent:event];
UITouch *touch = [touches anyObject];
//CGPoint curPt = [touch locationInView:self.view];
CGPoint newLocation = [touch locationInView:self.view];
CGPoint oldLocation = [touch previousLocationInView:self.view];
gameView.multipleTouchEnabled = true;
if(newLocation.x-oldLocation.x>0){
swipe_direction = 1;
//NSLog(@"left");
}
else{
swipe_direction = 2;
//NSLog(@"right");
}
if(swipe_direction==1){
//animate images
//play sound effect
}
else if(swipe_direction==2){
//animate images
//play sound effect
}
}
From the NSTimer documentation…
Your timer resolution is 10 milliseconds, so if the run loop doesn’t not complete quickly enough (under 10 milliseconds), you’ll start to notice a lag between real-time, and your counters.
If you are implementing a game, devs will generally try to disassociate from the CPU or clock speed.
Take a look at this answer
or take a look at how a framework like cocos2d implements its own scheduler.