It seems like at least once a week somebody asks why they can't display a UIActivityIndicatorView (or alert view), then perform a time-consuming synchronous task.
They are mystified that the activity indicator doesn't show up until after the time-consuming task is complete.
The reason it doesn't work is this: Cocoa queues up the user interface changes you make in your code, and applies them the next time your code returns and the application visits the event loop. So, if you do this:
Then the activity indicator doesn't actually display at all. The UI changes don't take place until after your code returns, and by then, the time-consuming work is over.
The key to fixing this is a method called performSelector:withObject:afterDelay:. That method lets you invoke a method in the future.
What you do is this:
Split out your time-consuming code into a separate method. Let's call the method doSomethingSlow.
<CODE>- (IBAction) someMethod
[theActivityIndicator startAnimating]; //Or whatever UI Change you need to make
[self performSelector: @selector(doSomethingSlow)
- (void) doSomethingSlow
//perform time-consuming tasks
[theActivityIndicator stopAnimating]; //Or whatever step to indicate that the task is done.
The code fragments above assume that you have already created an activity indicator view in interface builder and hooked it up as an outlet called theActivityIndicator.
Note that the exact same issue comes up with any user interface change you want to make before doing a time-consuming task, and the same solution works. Just change the line that starts the activity indicator animating to whatever UI change you want to make.
Post edited by Duncan C on
Animated GIF created with Face Dancer, available for free in the app store.