iPhone UIActivityIndicatorView not starting or stopping

jonnyv picture jonnyv · Dec 4, 2009 · Viewed 17.1k times · Source

When I call startAnimating on a UIActivityIndicatorView, it doesn't start. Why is this?

[This is a blog-style self-answered question. The solution below works for me, but, maybe there are others that are better?]

Answer

jonnyv picture jonnyv · Dec 5, 2009

If you write code like this:

- (void) doStuff
{
    [activityIndicator startAnimating];
    ...lots of computation...
    [activityIndicator stopAnimating];
}

You aren't giving the UI time to actually start and stop the activity indicator, because all of your computation is on the main thread. One solution is to call startAnimating in a separate thread:

- (void) threadStartAnimating:(id)data {
    [activityIndicator startAnimating];
}

- (void)doStuff
{ 
    [NSThread detachNewThreadSelector:@selector(threadStartAnimating:) toTarget:self withObject:nil];
    ...lots of computation...
    [activityIndicator stopAnimating];
}

Or, you could put your computation on a separate thread, and wait for it to finish before calling stopAnimation.