Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating UILabel in the middle of a for() loop

Tags:

objective-c

I have a method with a for() loop. In that loop, mylabel.text is updated many times. However, the actual label does not update on the screen until the method is done, updating with the last value created in the for() loop.

Using an NSLog, which does update in the middle of the for() loop, I see the value indeed changing for the label many times.

Is it the general practice in iOS to not update labels in the middle of the for() loop? I would imagine there is a way to do this.

like image 300
johnbakers Avatar asked Jun 15 '11 20:06

johnbakers


2 Answers

You can make the UI update by telling the run loop to run like this:

for (NSInteger i = 0; i < 10; i++) {
    [label setText:...];
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
}
like image 124
Morten Fast Avatar answered Nov 11 '22 19:11

Morten Fast


From my earlier comment:

Note that this (runMode:beforeDate:) can have all kinds of bizarre side-effects. When you call runMode:beforeDate:, all kinds of things could happen in the middle of your loop. Timers could fire; WebKit can do all kinds of madness; delayed selectors can fire. This is a very dangerous trick. Sometimes useful, occasionally necessary (especially on Mac), but not a general-purpose tool.

The better solution is to schedule your updates on the main dispatch queue:

for (NSInteger i = 0; i < 10; i++) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, i * NSEC_PER_SEC), 
                   dispatch_get_main_queue(), ^{
      [self.label setText:[NSString stringWithFormat:@"%d", i]];
    });
}

This schedules 10 updates 1 second apart. It can be adapted to all kinds of other requirements without creating a blocking method on the main run loop.

like image 8
Rob Napier Avatar answered Nov 11 '22 18:11

Rob Napier