Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How update a label periodically on iOS (every second)? [duplicate]

Tags:

uikit

iphone

I use a NSTimer which fires every second and updates a label which displays the remaining time until an event.

I works fine so far. The problem is while I am scrolling the TableView my Label does not update, because the MainThread is blocked by the touch/scroll event.

I thought about creating a second thread for the Timer but I couldn't update the label from a background thread anyways. I had to queue it with performSelector... on the MainThread where it would stuck like before.

Is there any way to update the label while scrolling?

like image 962
Alexander Theißen Avatar asked Jun 03 '11 16:06

Alexander Theißen


1 Answers

The problem is that a scheduledTimer will not get called while the main thread is tracking touches. You need to schedule the timer in the main run loop.

So instead of doing

[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateLabel:) userInfo:nil repeats:YES];

use

NSTimer* timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateLabel:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
like image 77
DHamrick Avatar answered Oct 21 '22 23:10

DHamrick