Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Using UIActivityIndicatorView when performing long synchronous tasks

Duncan CDuncan C Posts: 9,114Tutorial Authors, Registered Users @ @ @ @ @ @ @
edited June 2011 in Tutorial Discussion
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:
  1. start activity indicator
  2. do time-consuming work
  3. stop activity indicator
  4. 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];
  [self performSelector: @selector(doSomethingSlow) 
    withObject: nil 
    afterDelay: 0];
  return;
}

- (void) doSomethingSlow
{
   //perform time-consuming tasks
  [theActivityIndicator stopAnimating];
}


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.
Regards,
Duncan C
WareTo

widehead.gif
Animated GIF created with Face Dancer, available for free in the app store.

I'm available for one-on-one help at CodeMentor
Sign In or Register to comment.