I ended up using Grand Central Dispatch to handle this. The simplest way is to
- (void) doStuff
{
// Show wait on start
[myLoadingView setHidden:NO];
dispatch_queue_t queue = dispatch_queue_create("com.myDomain.myApp",null);
dispatch_async(queue, ^{
// Code to execute
{
//... Do my time consuming stuff here ...
// For testing purposes, I'm using
int i = 0;
while (i < 1000000000)
{
i++;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
// Hide Wait Screen on End
// ... also need to do any other UI stuff here ...
[myLoadingView setHidden:YES];
});
});
}
Unfortunately for me, my actual time consuming stuff
has some GUI changes in it (like showing alerts, preforming segues, changing labels, etc.). Instead of rewriting the whole thing to try to pull all the GUI stuff out, I discovered that nesting it all in another dispatch_async
, I can still get the waiting screen to show while the operations are performing, and all the other GUI stuff that is done in time consuming stuff
will update when it's done (after the waiting screen disappears).
- (void) doStuff
{
// Show wait on start
[myLoadingView setHidden:NO];
dispatch_queue_t queue = dispatch_queue_create("com.myDomain.myApp",null);
dispatch_async(queue, ^{
dispatch_async(dispatch_get_main_queue(), ^{
// Double nesting the dispatches seems to allow me to do UI changes as part of 'Code to execute' below.
// If I do not double nest like this, GUI behavior in "time consuming stuff" will be erratic
dispatch_queue_t queue2 = dispatch_queue_create("com.myDomain.myApp",null);
dispatch_async(queue2, ^{
dispatch_async(dispatch_get_main_queue(), ^{
// Code to execute
{
//... Do my time consuming stuff here - GUI changes will appear when all the code has finished running ...
// For testing purposes, I'm using
int i = 0;
while (i < 1000000000)
{
i++;
}
}
// Hide Wait Screen on End
[myLoadingView setHidden:YES];
});
});
});
});
}
Note that if doStuff
needs to return a value, you'll probably need to change it up a little to use a "completion block", detailed in the accepted answer here.