在后台实现一个块,然后在完成后在主线程上运行另一个块?

时间:2012-05-14 17:44:50

标签: cocoa-touch grand-central-dispatch nsthread

如何实施以下区块?

我需要在后台运行一些任务。 然后在后台任务完成后,一些任务将在主线程中运行。

为什么我使用块是因为我需要更新传递给此方法的视图。

- (void)doALongTask:(UIView *)someView {

    [self doSomethingInBackground:^{

        // Runs some method in background, while foreground does some animation.
        [self doSomeTasksHere];

    } completion:^{

        // After the task in background is completed, then run more tasks.
        [self doSomeOtherTasksHere];

        [someView blahblah];

    }];
} 

或者有更简单的方法来实现这个吗? 感谢。

1 个答案:

答案 0 :(得分:10)

我不确定您是否询问块如何工作或如何在主线程上运行完成处理程序。

根据您的代码,您调用doSomethingInBackground并传入两个块作为参数。必须在doSomethingInBackground方法中调用这些块才能运行。 doSomethingInBackground必须看起来像这样:

-(void)doSomethingInBackground:(void (^))block1 completion:(void (^))completion
{
    // do whatever you want here

    // when you are ready, invoke the block1 code like this
    block1();

    // when this method is done call the completion handler like this
    completion();
}

现在,如果您想确保在主线程上运行完成处理程序,您可以将代码更改为:

- (void)doALongTask:(UIView *)someView {

    [self doSomethingInBackground:^{

        // Runs some method in background, while foreground does some animation.
        [self doSomeTasksHere];

    } completion:^{
        // After the task in background is completed, then run more tasks.
        dispatch_async(dispatch_get_main_queue(), ^{
            [self doSomeOtherTasksHere];
            [someView blahblah];
        });
    }];
}

根据您编写的代码,这是我的答案。

然而,如果这个评论“我需要在后台运行一些任务。然后在后台任务完成后,一些任务将在主线程中运行”更能说明你实际上想要做什么然后你只需要这样做:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // do your background tasks here
    [self doSomethingInBackground];

    // when that method finishes you can run whatever you need to on the main thread
    dispatch_async(dispatch_get_main_queue(), ^{
        [self doSomethingInMainThread];
    });
});