Sun*_*day 3 asynchronous objective-c grand-central-dispatch
在我的iOS应用程序中,我在这样的后台线程上运行计算密集型任务:
// f is called on the main thread
- (void) f {
[self performSelectorInBackground:@selector(doCalcs) withObject:nil];
}
- (void) doCalcs {
int r = expensiveFunction();
[self performSelectorOnMainThread:@selector(displayResults:) withObject:@(r) waitUntilDone:NO];
}
Run Code Online (Sandbox Code Playgroud)
如何使用GCD运行昂贵的计算,使其不会阻塞主线程?
我已经看过dispatch_async了GCD队列选择的一些选项,但我对GCD来说太新了,感觉我已经足够理解了.
小智 10
您可以像建议的那样使用dispatch_async.
例如:
// Create a Grand Central Dispatch (GCD) queue to process data in a background thread.
dispatch_queue_t myprocess_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
// Start the thread
dispatch_async(myprocess_queue, ^{
// place your calculation code here that you want run in the background thread.
// all the UI work is done in the main thread, so if you need to update the UI, you will need to create another dispatch_async, this time on the main queue.
dispatch_async(dispatch_get_main_queue(), ^{
// Any UI update code goes here like progress bars
}); // end of main queue code block
}); // end of your big process.
// finally close the dispatch queue
dispatch_release(myprocess_queue);
Run Code Online (Sandbox Code Playgroud)
这是它的一般要点,希望有所帮助.