views:

96

answers:

2

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?

A: 

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.

v01d
I did this, and it works, but it also prevents the HUD from being displayed.
awakeFromNib
You could use NSTimer to poll and keep UI updates working correctly. It all depends on what you need. For a simple task and then update Derek's answer would be neater and less troublesome.
v01d
For a game engine or something more realtime a timer may already be in place anyway. Then sending off a thread and forgetting about it might be more what you need.
v01d
+3  A: 

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.

Derek Clarkson
This is nice system for UI updates; they can be a pain.
v01d