Cocoa touch 在后台实现一个块,然后在完成后在主线程上运行另一个块?
如何实现以下块 我需要在后台运行一些任务。 然后后台任务完成后,一些任务将在主线程中运行 之所以使用块,是因为我需要更新传递到此方法中的视图Cocoa touch 在后台实现一个块,然后在完成后在主线程上运行另一个块?,cocoa-touch,grand-central-dispatch,nsthread,Cocoa Touch,Grand Central Dispatch,Nsthread,如何实现以下块 我需要在后台运行一些任务。 然后后台任务完成后,一些任务将在主线程中运行 之所以使用块,是因为我需要更新传递到此方法中的视图 - (void)doALongTask:(UIView *)someView { [self doSomethingInBackground:^{ // Runs some method in background, while foreground does some animation. [self doSo
- (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];
}];
}
还是有更简单的方法来实现这一点?
谢谢。我不确定您是否在询问块是如何工作的,或者如何在主线程上运行完成处理程序 根据您的代码,您正在调用doSomethingInBackground并将两个块作为参数传入。必须在doSomethingInBackground方法中调用这些块才能运行。doSomethingBackground必须看起来像这样:
-(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];
});
}];
}
现在,如果要确保完成处理程序在主线程上运行,请将代码更改为如下所示:
-(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];
});
});
你的问题是什么?如何实现
doSomethingInBackground:completion:
,以便在主线程上调用完成处理程序?如果有其他/更简单的实施方式……在您的问题中,“这”意味着什么?