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?
views:
158answers:
3No, 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
.
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
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