gpt4 book ai didi

ios - 了解大中央调度

转载 作者:行者123 更新时间:2023-11-28 19:58:47 25 4
gpt4 key购买 nike

我看了很多关于它的话题,还是不清楚..

1)

当我做的时候:

dispatch_async(dispatch_get_main_queue(), ^(void) {
for(int i = 0; i < 10000000; i++)
{
NSLog(@" i = %i", i);
}
});

UI 卡住了,我无法点击任何按钮。如果我理解,那是因为它是在 dispatch_get_main_queue 上调用的,也就是说主线程?那么,如果 UI 被卡住,为什么还要谈论“背景”呢?

2)

dispatch_async(dispatch_get_main_queue(), {
self.tableData = results
self.appsTableView!.reloadData()
})
})

上下文:我从 api 服务取回一些数据 (session.dataTaskWithURL),当我收到所有信息时,我正在执行此调度。

但我不明白这些解释,我引用:

"Because this task happens in the background, we need to jump in to the foreground before we update the UI. So we need to use dispatch_async to move back in to the main thread, and reload the table view."

嗯??这是因为 session url 在后台,现在有必要回到主线程?如果我们不回来怎么办?

3) 我听说从另一个线程更新 UI 是不安全的。为什么?

4) 一点 HS,但会很好:现在,我正在等待请求完成以接收所有信息并将其显示到 UI。例如可以是 3 秒。在这几圈驯服期间,用户界面是空的。是否可以在收到数据后一点一点地在 UI 中显示信息,而不是等待请求完成?

非常感谢大家!

最佳答案

1) 您要分派(dispatch)到主线程,因此这将是一个阻塞操作。相反,您想分派(dispatch)到不同的线程。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {

// this is on a background thread
for (int i = 0; i < 10000000; i++) {

NSLog(@"i = %i", i);

}

dispatch_async(dispatch_get_main_queue(), ^(void) {

NSLog(@"Done - this is on the main thread.");

});

});

2) 您之前所在的分派(dispatch) block 在后台,所以现在您分派(dispatch)到该 block 内的主线程来执行 UI 任务(所有 UI 任务必须在主线程上执行)。

3) 来自文档:

Note: For the most part, UIKit classes should be used only from an application’s main thread. This is particularly true for classes derived from UIResponder or that involve manipulating your application’s user interface in any way.

4) 当一些后台任务完成后,你肯定可以调用主线程来更新UI。例如:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {

for (int i = 0; i < 10000000; i++) {

NSLog(@"i = %i", i);
if (i % 1000000 == 0) {

dispatch_async(dispatch_get_main_queue(), ^(void) {

NSLog(@"Another million is done (this is on the main thread)");

});

}

}

dispatch_async(dispatch_get_main_queue(), ^(void) {

NSLog(@"Done - this is on the main thread.");

});

});

关于ios - 了解大中央调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25099863/

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