It seems like at least once a week somebody asks why they can't display a UIActivityIndicatorView, 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
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
[self performSelector: @selector(doSomethingSlow)
- (void) doSomethingSlow
//perform time-consuming tasks
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.
Animated GIF created with Face Dancer
, available for free in the app store.
I'm available for one-on-one help at CodeMentor