9

I have an NSTimer

timer = [NSTimer scheduledTimerWithTimeInterval:1 
                                         target:self 
                                       selector:@selector(periodicTimer) 
                                       userInfo:nil 
                                        repeats:YES];

which does

- (void)periodicTimer
{
    NSLog(@"Bang!");
    if (timerStart != nil)
        [timerLabel setText:[[NSDate date] timeDifference:timerStart]];        
}

The problem is that while scrolling a tableview (or doing other tasks) the label doesn't get updated, furthermore, "Bang!" doesn't appear, so I supposed the method doesn't get called.

My question is how to update the label periodically even when the user is playing around with the app interface.

Fr4ncis
  • 1,387
  • 1
  • 11
  • 23
  • is the code shown in `periodicTimer` above really all that happens periodically? you just need to update a label that displays a time? or is there more involved background processing? – Nate May 26 '12 at 10:26
  • It is all that happens periodically (NSLog was just a test to see if the method at least gets called) – Fr4ncis May 26 '12 at 11:22

2 Answers2

27

You'll need to add your timer to the UITrackingRunLoopMode to make sure your timer also fires during scrolling.

NSRunLoop *runloop = [NSRunLoop currentRunLoop];
NSTimer *timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(myTimerAction:) userInfo:nil repeats:YES];
[runloop addTimer:timer forMode:NSRunLoopCommonModes];
[runloop addTimer:timer forMode:UITrackingRunLoopMode];

From: https://stackoverflow.com/a/1997018/474896

Community
  • 1
  • 1
Joris Kluivers
  • 11,894
  • 2
  • 48
  • 47
  • Yes, this is the right way to handle this problem. I started prototyping my solutions before the poster replied that his periodicTimer function was not a simplification for the sake of asking the question, but that he truly didn't have anything going on besides changing a text label. So, no need to use background work as the UI update is all there is. +1 – Nate May 26 '12 at 12:11
  • 6
    FYI - NSRunLoopCommonModes includes UITrackRunLoopMode as of iOS 7 – Matt S. Nov 04 '13 at 19:41
-2

Not sure about this one, but my first guess would be that the main thread on which the interface is being rendered your timer just doesn't get a chance to do anything while its updating the interface.

You could create a new thread with a new run loop for your timer, but that is a bit of an ugly solution maybe. What functionality in your app are you trying to achieve? Maybe we can advise a better strategy than using a timer.

Antwan van Houdt
  • 6,989
  • 1
  • 29
  • 52
  • The functionality is the timer itself. I think it's a problem about NSTimer not being called while the main thread is taking care of the UI scrolling. – Fr4ncis May 26 '12 at 11:24