Juan M. Juan M. - 1 year ago 107
iOS Question

Timer that updates label running in background

I have coded a timer using an NSTimer that updates a label. The problem is that in the same viewcontroller I have a uitableview and when I scroll it down, the timer doesn't update its value so the user can "cheat" to stop the timer.

I think this could be easy to fix with a serial queue with CGD but I don't figure out how to do it.

Thanks in advance,


Answer Source

First of all keep in mind that you cannot perform UI changes in any other thread than the main thread. Having said that, you need the NSTimer to fire in the main queue, otherwise the program will crash when changing the UILabel. Have a look at this links http://bynomial.com/blog/?p=67 and this one http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSRunLoop_Class/Reference/Reference.html

To my knowledge, if you schedule the timer in the for the NSRunLoopCommonModes it will ignore event updates and fire the timer jsut how you want it:

 NSTimer *timer = [NSTimer timerWithTimeInterval:1.0
                                         userInfo:nil repeats:YES];
  [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

-(void) timerDidTick:(NSTimer*) theTimer{
    [[self myLabel] setText:@"Timer ticked!"];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download