Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run an UIActivityIndicatorView while the main thread is busy

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.

like image 640
Seva Alekseyev Avatar asked Mar 06 '10 04:03

Seva Alekseyev


2 Answers

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.

like image 120
Ed Marty Avatar answered Nov 03 '22 01:11

Ed Marty


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.

like image 26
marcc Avatar answered Nov 03 '22 01:11

marcc