I have a connected UILabel
@property (strong, nonatomic) IBOutlet UILabel *label;
And an Action, which is triggered by the button
- (IBAction)buttonPressed:(UIButton *)sender;
When button is pressed, i'd like to update the label to display running seconds up to 3 minutes, so i
- (IBAction)buttonPressed:(UIButton *)sender {
for (int i =0; i < 180; ++i) {
[label setText:[NSString stringWithFormat:@"%d", i]];
sleep(1);
}
}
Confirmed, method is called, timer is ticking ..the label text however does not change. What am i doing wrong please?
your sleep() is in the main thread , your view cannot refresh , you can ues NSTimer to do it.
All UI related things are done in the main thread. Forcing your runtime to sleep on the main thread will literally freeze your UI. Do it 180 times and you got one frustrated end-user.
You have to exit back to your runloop to allow the control to refresh. You should probably use an NSTimer that fires every second or so instead of a tight loop.
Although not really recommended, the following might also work if you call it right after setText:
The
sleep()
does not allow the UI thread to update itself.Here is a sample using GCD that closely matches you original code. Note: there are better ways to do this (see:
dispatch_after()
).