0

I need to update some user interface objects by timer, but when I touch slider with continuous action everything freeze beside slider. in iOS this version work fine, but in mac os x some problems :(

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    tick = 0;

    [NSTimer scheduledTimerWithTimeInterval:0.25f
                                     target:self
                                   selector:@selector(timerTick)
                                   userInfo:nil
                                    repeats:YES];
}

- (void)timerTick
{
    tick++;
    [self.labelTest setIntegerValue:tick];
}

- (IBAction)sliderAction:(id)sender
{
    // do something 
    NSLog(@"%g", [self.sliderMain doubleValue]);
}

1 Answers1

1

You should add your timer to main run loop:

[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

And also you should create instance variable or property, for example:

@property (strong, nonatomic) NSTimer *timer;

And before you create timer I would recomentded you to use lazy initialization:

if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.25f
                                     target:self
                                   selector:@selector(timerTick)
                                   userInfo:nil
                                    repeats:YES];
    }
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

And when you close the app or the app goes to background you can invalidate timer:

[self.timer invalidate];
self.timer = nil;

Hope this help.

Greg
  • 25,317
  • 6
  • 53
  • 62
  • I wonder if it's a bit inefficient that you have scheduled the timer in the default run loop mode twice? If you're going to add the timer in common modes, you could create the timer with one of the methods that doesn't also schedule the timer. – JWWalker Dec 26 '13 at 03:12