4

I have strange issue with timer. timer is updating well within application. i am showing the code.

// Start Timer

#pragma mark- Timer
- (void)startTimer
{
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
}

// Update Timer

- (void)updateTimer:(NSTimer *)theTimer
{
    NSLog(@"called"); 
}

Problem: I have a textview when i scroll text within the textview the updateTimer method stops calling and when I stop scrolling then it starts to update timer.

Now what to do to continue calling the update timer method?

Sunny Shah
  • 12,990
  • 9
  • 50
  • 86

2 Answers2

5

For do fix this issue you need to add your NSTimer to the mainRunLoop. Such like,

- (void)startTimer
{
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
iPatel
  • 46,010
  • 16
  • 115
  • 137
  • 1
    If you're going to add the timer to the runloop manually (which you need to to fix this problem), you should use timerWithTimeInterval:target:selector:userInfo:repeats:, instead of scheduledTimer... – rdelmar May 29 '14 at 05:22
  • @iPatel can u explain this answer in simple words why need to use – Sunny Shah May 29 '14 at 05:28
  • @SunnyShah - http://stackoverflow.com/questions/9918103/nstimer-requiring-me-to-add-it-to-a-runloop – iPatel May 29 '14 at 05:31
  • I think while a UIScrollView (or a derived class thereof) is scrolling, it seems like all the NSTimers that are running get paused until the scroll is finished thats why this happens. – Banker Mittal May 29 '14 at 05:54
  • @rdelmar - Thanks, can you explain me why `timerWithTimeInterval:target:selector:userInfo:repeats` is better for us when we are use of `NSRunLoop`. – iPatel May 29 '14 at 05:56
  • @rdelmar please add the full answer above line is not working – Sunny Shah May 29 '14 at 06:01
  • @iPatel, because scheduledTimer automatically adds the timer to the runloop in the default mode. You then add it to the runloop in common mode. I don't know whether that adds it twice or not, but the only reason to use the scheduledTimer version is to get the automatic adding to the runloop -- if its adding it in the wrong mode for your use, why use it? – rdelmar May 29 '14 at 06:01
0

You can do this way also,

 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.001 
                                                             target:self 
                                                           selector:@selector(updateTimer:) 
                                                           userInfo:nil 
                                                            repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer 
                             forMode:NSRunLoopCommonModes];
Banker Mittal
  • 1,918
  • 14
  • 26