ARe*_*ity 2 cocoa-touch nsthread grand-central-dispatch
如何实现以下块?
我需要在后台运行一些任务.然后在后台任务完成后,一些任务将在主线程中运行.
为什么我使用块是因为我需要更新传递给此方法的视图.
- (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];
}];
}
Run Code Online (Sandbox Code Playgroud)
或者有更简单的方法来实现这个?谢谢.
Ste*_*veB 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();
}
Run Code Online (Sandbox Code Playgroud)
现在,如果您想确保在主线程上运行完成处理程序,您可以将代码更改为如下所示:
- (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];
});
}];
}
Run Code Online (Sandbox Code Playgroud)
根据您编写的代码,这是我的答案.
但是,如果这个评论"我需要在后台运行一些任务.然后在后台任务完成后,一些任务将在主线程中运行"更能说明你实际上要做什么然后你只需要这样做:
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];
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3543 次 |
| 最近记录: |