Can I start a thread by pressing a button in a coc

2019-08-03 17:47发布

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条回答
走好不送
2楼-- · 2019-08-03 18:09

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

查看更多
爷、活的狠高调
3楼-- · 2019-08-03 18:12

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
查看更多
叛逆
4楼-- · 2019-08-03 18:22

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.

查看更多
登录 后发表回答