Search code examples
objective-ccocoacontinuoussimultaneous

Xcode cocoa simultaneously update interface by timer and continuous action by slider


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]);
}

Solution

  • 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.