View Full Version : Update view in middle of thread?

Dec 27, 2008, 02:28 PM
I have a calculation that can take a while sometimes depending on user input. Sometimes it's instant and sometimes it takes several minutes. I've already implemented a cancel button if the user doesn't want to wait. I'd also like to have a progress bar to display how much longer it will take. I can calculate the progress bar value easily, but I am having trouble with getting it to update.

I've tried using:

[self.view setNeedsDisplay];


CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, YES);

but neither seem to be working for me. I've tried running the calculation loop in the background and using:

[self performSelectorOnMainThread:@selector(progressUpdate) withObject:f waitUntilDone:YES];

where progressUpdate is a new method that accepts "f" as an argument to update the UIProgressView.

Does anyone know what the best way to update a progress bar is while the loop that is calculating it is still running? The above things that I tried were suggestions I saw in other threads for similar problems.



I have this working now. I used [NSThread detachNewThreadSelector: ... ]; to start the loop for the calculation. This loop also calculates the value for the progress indicator and stores it in a variable defined in the header file.
Then I used another [NSThread detachNewThreadSelector: ... ]; to run a loop on a [self performSelectorOnMainThread: ...]; that set the value of the progress indicator.

It did not work if I updated the progress value in the new thread without calling performSelectorOnMainThread.
It did not work if I moved the performSelectorOnMainThread to the loop for the calculation and commented out the detachNewThreadSelector for the progress thread.

This will work for now, but if anyone know of a better way, please let me know. Also, I don't like running the calculation loop in a new thread as it severely slows down the calculation. This is just with testing on the simulator. I have yet to see what it looks like on the device.