gpt4 book ai didi

objective-c - 用 GCD 替换 performSelectorInBackground

转载 作者:搜寻专家 更新时间:2023-10-30 19:54:02 25 4
gpt4 key购买 nike

在我的 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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18344532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com