Objective-c – UIProgressView do not update in loop

objective cuiprogressview

I am loading a file and would like to show the progress in a UIProgressView. I can set the initial with:

[loadingProgressView setProgress: 0.00];

..in viewDidLoad this works perfectly.

The only thing I want to do then is to add 0.1 to the bar each loop but it does not update:

 while (eOF != 99999) {

    ...

    [loadingProgressView setProgress:loadingProgressView.progress + 0.10];

 }

I have checked around but not really found anything around just updating the bar each time I loop.

Anyone that can share some advice around this?

—UPDATE—

tried this without success:

while (eOF != 99999) {

    ...

    [loadingProgressView setProgress:loadingProgressView.progress + 0.10];
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate date]];

 }

Best Answer

You are looping through your while loop blocking the main thread, UI elements will not be able to refresh until the main thread becomes available. The best way around this is to run this code in a background thread (making the UI call on the main thread).

Or (I'm not sure about this one, see this discussion) you let the main thread some breathing space by calling

NSDate* futureDate = [NSDate dateWithTimeInterval:0.001 sinceDate:[NSDate date]];
[[NSRunLoop currentRunLoop] runUntilDate:futureDate];
Related Topic