Reputation: 69
How do I implement the following block?
I need to run some tasks in background. Then after the background task is completed, some tasks will be run in main thread.
Why I use blocks is because i need to update a view that is passed into this method.
- (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];
}];
}
Or is there an easier way to implement this? Thanks.
Upvotes: 2
Views: 3589
Reputation: 662
I'm not sure if you are asking about how blocks work or how to run your completion handler on the main thread.
Based on your code you are calling doSomethingInBackground and passing in two blocks as parameters. Those blocks will have to be invoked in your doSomethingInBackground method in order to run. doSomethingInBackground would have to look something like this:
-(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();
}
Now if you want to make sure your completion handler is run on the main thread you would alter your code to look like this:
- (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];
});
}];
}
That's my answer based on the code you wrote.
However, if this comment "I need to run some tasks in background. Then after the background task is completed, some tasks will be run in main thread" is more indicative of what you are actually trying to do then you just need to do this:
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];
});
});
Upvotes: 10