objective-c – 用GCD替换performSelectorInBackground

在我的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];
}

如何使用GCD运行昂贵的计算,使其不会阻塞主线程?

我已经看过dispatch_async以及GCD队列选择的一些选项,但我对GCD太新了,感觉我已经足够了解它.

最佳答案
您可以像建议的那样使用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);

这是它的一般要点,希望有所帮助.

转载注明原文:objective-c – 用GCD替换performSelectorInBackground - 代码日志