views:

570

answers:

2

Hi all,

is there a way to display the animated spinning wheel while the main thread does a lengthy operation? The animation is handled by the same thread that created the UIActivityIndicatorView, right? If so, can views that belong to several threads sit in the same view hierarchy?

All else failing, I don't mind moving a lengthy operation itself into a background thread, but then I'd have to freeze the UI somehow while it's running. That I'm not sure how to do.

EDIT: "lengthy" is around 2 sec on a 1st-gen device.

+2  A: 

The solution is to start the animation at least one iteration through the run loop before running the lengthy operation. For example:

[activity startAnimating];
[self performSelector:@selector(lengthyOperation) withObject:nil afterDelay:0];

You don't have to use the performSelector method, just some way to set the method to run later so the activity indicator has a chance to start animating before you get busy.

Ed Marty
Heck, I was close :) Tried performSelectorOnMainThread, but it seems like delay was the key.
Seva Alekseyev
@Seva Running lengthy operations on the main thread is generally a bad idea.
Giao
What Giao says is true. However, if you need the application to pause while it's happening, it doesn't seem like a TERRIBLE idea. A better solution, however, might be to use [[UIApplication sharedApplication] beginIgnoringInteractionEvents] and endIgnoringInteractionEvents when you're done.
Ed Marty
I have to agree with Giao; the main thread/run loop should *never* be stalled--the OS will terminate an application that has its main thread stalled for too long.
rpetrich
+3  A: 

The right answer is definitely to move the lengthly operation to a background thread and have it communicate to the main thread when it's done. If you don't know how to do this, read on NSOperationQueue and NSInvocationOperation. Your app and your users will thank you for the minimal time it will take to learn.

marcc