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

标签 objective-c ios cocoa-touch background-process

我正在尝试在我的 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/

相关文章:

ios - 具有相同索引的不同对象的 NSMutableArray 的奇怪行为

ios - 整数属性的观察者

ios - 如何处理 phonegap cordova 上的 iOS 通知回调?

ios - 在 Swift 中查看模型绑定(bind)

ios - 带有左+右大写字母和中间图案的 UIButton

objective-c - 找不到 Cocoapods podspec 依赖项导入文件

ios - AVAudioRecorder 不保存录音

ios - 提示用户输入并存储数据

cocoa-touch - UIButton 上的文本更改不会保留

ios - 为什么 UIApplicationMain 函数被命名为类命名风格