What we’re trying to accomplish
Say you have class BackgroundTask that retains a block elsewhere and will run it in your app like so:
1 2 3 4 5 6 7 8 9 10 11 |
@interface BackgroundTask () { } @property (copy, nonatomic) OnBackgroundTask task; ... ... -(void)run { self.task(); // execute that task } |
The block of code that property task points to is something like this:
1 2 3 4 5 6 7 8 9 10 |
for(int i = 0; i < 20; i++) { NSLog(@"%s - processing...%d", __FUNCTION__, i); if(i == 8) { //want to reply to BackgroundTask to do something break; } } |
So somewhere within the task, when we reach a certain point, we want to communicate to Background task that we want it to do say, do some clean up. How do we communicate back to BackgroundTask?
Solution – Pass in a reply block
1) declare a block with a block parameter
1 |
typedef void (^OnBackgroundTask) (CleanUpBackgroundTask cleanup); |
This means that we declare a block called OnBackgroundTask, which returns void. However, it does take 1 parameter of type CleanUpBackgroundTask.
where CleanUpBackgroundTask returns void and takes no parameters
1 |
typedef void (^CleanUpBackgroundTask) (); |
We will be using CleanUpBackgroundTask to communicate back to BackgroundTask.
2) declare the reply block with code definition, then pass it into the original block during the call
So when using the code, you provide a block of code for the task like so:
1 2 3 4 |
[[BackgroundTaskManager singleton] addBackgroundTask:^(CleanUpBackgroundTask cleanUp) { // your code task here cleanUp(); }]; |
self.task now points to the block of code you just provided. cleanup block currently is not defined. We can define it right before you call self.task and pass it in.
1 2 3 4 5 6 7 8 9 |
CleanUpBackgroundTask backgroundTaskCleanUp = ^{ NSLog(@"%s ----------- OnFinishTask BLOCK for %@----------------", __FUNCTION__, self.taskName); [self cleanup]; }; ... ... self.task(backgroundTaskCleanUp); // code 'task' will now run |
At this point, the task code is called, your code task will run, and the cleanUp() will naturally be called within code ‘task’.