Search code examples
cocoansviewnstimer

How to ensure NSTimer always runs in NSView?


I have an NSTimer inside a custom NSView. The timer is set to always repeat at a specific interval and once it fires, the timer should update a bunch of view parameters.

This all works fine but, when the view is out of focus (i.e. right clicking on the tool bar to pull up a menu), the timer is delayed and does not fire during the time when the view is out of focus.

My question, is how do I ensure that the timer always fires and updates the view parameters even when the view is out of focus?


Solution

  • When you perform certain events (such as displaying a context menu), the run loop will enter event tracking mode. This means that only certain events will be handled. To get your timer to fire while the run loop is in this mode, include NSEventTrackingRunLoopMode in the list of modes for the timer.

    NSTimer *timer = [NSTimer timerWithTimeInterval:theInterval target:theTarget selector:theSelector userInfo:theUserInfo repeats:shouldRepeat];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSEventTrackingRunLoopMode];