如何实现以下 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/