等到后台选择器完成以调用新方法

DGu*_*und 2 cocoa-touch objective-c background-process ios

我正试图在我的观点负载上从互联网上获取数据.为了不滞后用户界面,我正在使用执行HTML下载和解析

[self performSelectorInBackground:@selector(alertThreadMethod) withObject:nil];
Run Code Online (Sandbox Code Playgroud)

检查是否有在线提醒.但是为了在视图上显示信息,iOS表示我需要使用主线程.所以我在之后调用显示代码:

[self performSelectorInBackground:@selector(alertThreadMethod) withObject:nil];
[self loadAlert];
Run Code Online (Sandbox Code Playgroud)

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

我怎样才能确保[self loadAlert];之后的运行?或者有更好的方法吗?

Rob*_*Rob 5

您可以将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);
Run Code Online (Sandbox Code Playgroud)

或者,如果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);
Run Code Online (Sandbox Code Playgroud)

顺便说一下,如果你只是在后台执行这一项任务,而不是创建自己的串行队列,那么你可能只使用一个现有的后台队列.如果您需要串行特性,则只需要创建一个队列(即,您将要进行多次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];
    });
});
Run Code Online (Sandbox Code Playgroud)