0

I can't find a clear answer on how to update the progress of a UIProgressbar whilst iterating a loop e.g. :

for (int i=0;i<items.count;i++) {
    Object *new = [Object new];
    new.xxx = @"";
    new...
    ...
    float progress = (i+1) / (float)items.count;
    progressBar.progress = progress;
}
[self save];

how can I update the UI on a seperate thread?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Halpo
  • 2,982
  • 3
  • 25
  • 54
  • Perform the long running process on a background thread and update the UI on the main thread. This is a perfect use of Grand Central Dispatch (GCD). – rmaddy Jul 11 '14 at 18:04

1 Answers1

1

Run the loop on a background thread, and update the progress bar on the main thread:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    for (int i=0;i<items.count;i++) {
        Object *new = [Object new];
        new.xxx = @"";
        new...
        ...
        float progress = (i+1) / (float)items.count;
        dispatch_async(dispatch_get_main_queue(), ^{
            progressBar.progress = progress;
        });

    }
    [self save];
});
Fabian
  • 6,973
  • 2
  • 26
  • 27