我不确定您是否在询问块如何工作或如何在主线程上运行完成处理程序。
根据您的代码,您正在调用 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];
});
});