cocoa-touch - 在后台实现一个 block ,然后在完成后在主线程上运行另一个 block ?

标签 cocoa-touch grand-central-dispatch nsthread

如何实现以下 block ?

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

为什么我使用 block 是因为我需要更新传递给这个方法的 View 。

- (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];

    }];
} 

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

最佳答案

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

根据您的代码,您正在调用 doSomethingInBackground 并将两个 block 作为参数传递。必须在您的 doSomethingInBackground 方法中调用这些 block 才能运行。 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];
    });
});

关于cocoa-touch - 在后台实现一个 block ,然后在完成后在主线程上运行另一个 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10588412/

相关文章:

iOS的dispatch_get_global_queue嵌套在dispatch_get_main_queue中

ios5 - 大中央调度。如何查询队列以查看它是否正在使用?

swift - Xcode 9.0 中的线程问题

iphone - 如何运行另一个线程并使用该线程运行计时器来重复进程?

objective-c - 如何使用角 handle 调整 UIView 的大小 - 类似于 'Pages' , 'Keynote'

objective-c - UIView 在 iOS 设备上不透明,但在模拟器上是透明的

swift - DispatchGroup 未在 Swift 中通知 'Main"

ios - ios 5.1 中的自动刷新 uiviewcontroller

ios - Facebook SDK 共享始终返回 sharerDidCancel

ios - 如何在 iOS 上检测和显示设备信息