LuckyLuke
LuckyLuke

Reputation: 49057

NSTimer to update label

self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimerDisplay) userInfo:nil repeats:YES];
[runLoop addTimer:self.timer forMode:NSRunLoopCommonModes];

This code-snippet is copied from my viewDidLoad method, so it is runned from the main-thread. All it do is to call a method to update a label.

I thought I need to have a own thread for doing this, but after getting help on this at SO I figured out that I did not.

However, I do not understand the NSRunLoopCommonModes. Why does it work?


AND the timer updates the label which is a "digital counter" which is on the same screen as a tableview so it CAN'T stop the timer even if the user holds the screen.

Thanks.

Upvotes: 0

Views: 1085

Answers (3)

Thomas Zoechling
Thomas Zoechling

Reputation: 34243

A NSRunLoop can run in different input modes. The mode defines which events are handled by the current runloop.
e.g.: If the current runloop is in event tracking mode, it only handles modal event loops. (e.g. dragging a NSScrollBar or a NSSlider on the Mac)

If you add your NSTimer only for NSDefaultRunLoopMode it won't fire if something is causing a modal event loop. (Details in Apple's documentation)

NSRunLoopCommonModes is an "alias" for multiple modes so that you don't have to do:

[[NSRunLoop currentRunLoop] addTimer:mRenderDurationTimer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer:mRenderDurationTimer forMode:NSModalPanelRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer:mRenderDurationTimer forMode:NSEventTrackingRunLoopMode];

Upvotes: 2

AechoLiu
AechoLiu

Reputation: 18368

If you add your time to an instance of NSRunLoop under another thread, you need a while loop for this NSRunLoop of the thread. It looks like following:

do {
   [[NSRunLoop currentRunLoop] runUntilDate:[NSDate date]];
} while (bDone);

Normally, I add the above code on my thread main function, and when thing is done, the thread go die and the autorelease pool of the thread will be released.

Upvotes: 0

Thomas Joulin
Thomas Joulin

Reputation: 6650

I don't think you have to have this line at all, the first line is enough... I use PSYBlockTimer in my code which derives from the SDK method you use, but instead of a selector calls a block :

self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:NO usingBlock:^ (NSTimer *t)
{
    // stuff that will get executed in a second
}];

Upvotes: 0

Related Questions