views:

158

answers:

3

I have a Cocoa interface. When I press a button I want to process some data, but I want to keep using the interface while it's working. I guess the only solution is NSThread. Now will there be a locking mechanism preventing me from returning from an IBAction method if it spawns a thread?

+3  A: 

No, there is no locking mechanism. The new thread will start and the current thread will continue. You may want to look at performSelectorInBackground:withObject: and possibly NSOperation in addition to NSThread.

Tom Dalling
A: 

Don't know much about cocoa, but starting a new thread for processing something in background while keeping the UI thread free for taking user inputs(and thus preventing UI from freezing) is the most widely used technique for the problem you have mentioned.Both threads will work together (concurrently) and the programmer has to take care of the synchronization issues if any.You should go ahead with the technique without doubt.

Thanks, Sourabh

sourabh jaiswal
+2  A: 

Take a look at NSOperation. NSOperation is one of the few cocoa classes which must be subclassed for it to be useful. By adding a delegate property to your NSOperation subclass you can get notified when the operation completes. Also, you can add a userInfo property to allow the operation to pass back arbitary data to the delegate

@implementation MyNSOperationSubclass

-(void)main
{
    //do operation here



    //operationResult is used to report back to the delegate. operationResult could include a userInfo key so that the delegate can have some data passed back, or an error key to indicate success of the operation.
    NSDictionary *operationResult; 


    //Some checks to ensure that the delegate implements operationHasFinished: should be added.
    //waitUntilDone: YES locks the main thread
    [[self delegate] performSelectorOnMainThread:@selector(operationHasFinished:)     withObject:operationResult waitUntilDone: YES];

}

@end
Benedict Cohen
will the delegate be able to send messages while it is still processing so I can animate my interface as the data is being processed by the thread?
yan bellavance
Yes. NSOperation encapsulates threading. Therefore the processing your NSOperation subclass performs will not interfere with your main thread (or any other thread for that matter). The only time the NSOperation impacts on the main thread is when it calls performSelectorOnMainThread:, but that is by design and is desired behaviour.
Benedict Cohen