I'm trying to use a method from a class I downloaded somewhere. The method executes in the background while program execution continues. I do not want to allow program execution to continue until this method finishes. How do I do that?
I'd suggest wrapping up call to the class method in your own method, and set a boolean once it completes. For eg:
BOOL isThreadRunning = NO;
- (void)beginThread {
isThreadRunning = YES;
[self performSelectorInBackground:@selector(backgroundThread) withObject:nil];
}
- (void)backgroundThread {
[myClass doLongTask];
// Done!
isThreadRunning = NO;
}
- (void)waitForThread {
if (! isThreadRunning) {
// Thread completed
[self doSomething];
}
}
How you wish to handle waiting is up to you: Perhaps polling with [NSThread sleepForTimeInterval:1] or similar, or sending self a message each run loop.
My first inclination is to not do what you are suggesting. The technique I've used before is to give the thread a selector to a method in the originating object (which is on the main thread). When the second thread is started, the main thread keeps executing, but puts up a busy indicator of some sort on the display. This allows user interaction to continue if required.
When the second thread ends, just before it shuts down, it calls the selector on the main thread. The method that the selector references then removes the busy indicator from the display and tells the main thread to update, picking up whatever data the second thread has generated.
I've used this successfully for an app which accesses a web service (on the second thread) and then updates the display once data is returned without locking it. This makes the user experience much nicer.