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:
- start activity indicator
- do time-consuming work
- stop activity indicator
- return
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.
- (IBAction) someMethod
{
[theActivityIndicator startAnimating]; //Or whatever UI Change you need to make
[self performSelector: @selector(doSomethingSlow)
withObject: nil
afterDelay: 0];
return;
}
- (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.
Regards,
Duncan C
WareTo

Animated GIF created with
Face Dancer, available for free in the app store.
I'm available for one-on-one help at
CodeMentor
Replies
This post belongs in tutorials, not tutorial discussion. I just got very puzzled when I went to link it to somebody who asked the same question again. I couldn't find it!
Anyway, I re-posted the thread where it belongs. Can somebody kill this thread in "Tutorial discussion"?
Thanks, and sorry for the mess-up.
Duncan C
WareTo
Animated GIF created with Face Dancer, available for free in the app store.
I'm available for one-on-one help at CodeMentor