我有这样的方法:
- (BOOL)shouldDoSomeWork {
BOOL result = // here I need do hard work with data in background thread and return result, so main thread should wait until the data is calculated and then return result;
return result;
}
如何实施?
我有这样的方法:
- (BOOL)shouldDoSomeWork {
BOOL result = // here I need do hard work with data in background thread and return result, so main thread should wait until the data is calculated and then return result;
return result;
}
如何实施?
您是否正在寻找这个:
-(void) startWork
{
//Show activity indicator
[NSThread detachNewThreadSelector:@selector(doSomeWork) toTarget:self withObject:nil];
}
-(void) doSomeWork
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
//Do your work here
[pool release];
[self performSelectorOnMainThread:@selector(doneWork) withObject:nil waitUntilDone:NO];
}
-(void) doneWork
{
//Hide activity indicator
}
示例如何使用 GCD 进行操作:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Your hard code here
// ...
//BOOL result = ...
dispatch_async(dispatch_get_main_queue(),^{
[self callbackWithResult:result]; // Call some method and pass the result back to main thread
});
});
这通常不是你会做的。你需要一些结构更像这样的东西:
- (void)doSomeWorkAndThen:(^void)block {
dispatch_async(dispatch_get_global_queue(0, 0), ^ {
// do
// some
// work
dispatch_sync(dispatch_get_main_queue(), ^ {
block();
});
});
也就是说,您将请求和之后的操作保存在一个地方。
常见的 建议是使用可用的最高抽象级别来执行任务。因此,NSThread
在您可以在后台执行工作的事情列表中应该相对较低。
您调查 API 的顺序应该是这样的:
使用前两个,您将代码编写为“工作单元”,然后将此工作放在队列中以在某个时候执行。系统会为您创建和销毁线程,并且 API 易于使用。这是一个使用NSOperationQueue
.
NSBlockOperation * blockOperation = [NSBlockOperation blockOperationWithBlock:^{
//Do work
//update your UI on the main thread.
[self performSelectorOnMainThread:@selector(workDone:) withObject:workResults waitUntilDone:NO];
}];
[self.operationQueue addOperation:blockOperation];
就这么简单。