gpt4 book ai didi

objective-c - 等到后台选择器完成调用新方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:19:35 26 4
gpt4 key购买 nike

我正在尝试在我的 View 负载上从 Internet 获取数据。为了不滞后于 UI,我使用

执行 HTML 下载和解析
[self performSelectorInBackground:@selector(alertThreadMethod) withObject:nil];

检查是否有在线警报。然而,为了在 View 上显示信息,iOS 说我需要使用主线程。所以我在之后立即调用显示代码:

[self performSelectorInBackground:@selector(alertThreadMethod) withObject:nil];
[self loadAlert];

这样做时,[self loadAlert]; 实际上在后台选择器之前运行(速度更快)。因此,它没有后台选择器应该提供的信息。

如何确保 [self loadAlert]; 在之后运行?或者有更好的方法吗?

最佳答案

您可以将 loadAlert 调用移动到 alertThreadMethod 中或使用 Grand Central Dispatch串行队列,例如,

dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
[self alertThreadMethod];
[self loadAlert];
});
dispatch_release(queue);

或者,如果 loadAlert 正在更新 UI,因为您在主队列中进行 UI 更新,您会执行如下操作:

dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
[self alertThreadMethod];
dispatch_async(dispatch_get_main_queue(), ^{
[self loadAlert];
});
});
dispatch_release(queue);

顺便说一下,如果您只是在后台执行这一项任务,而不是创建您自己的串行队列,您可能只使用现有的后台队列之一。如果你需要串行性质,你只需要创建一个队列(即你将有大量的 dispatch_async 调用并且你不能让它们同时运行)。但在这种简单的情况下,这可能会更有效一些,绕过串行队列的创建和释放:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
[self alertThreadMethod];
dispatch_async(dispatch_get_main_queue(), ^{
[self loadAlert];
});
});

关于objective-c - 等到后台选择器完成调用新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11147279/

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