Passing Blocks as parameter to other Blocks

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:

The block of code that property task points to is something like this:

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

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

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:

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.

At this point, the task code is called, your code task will run, and the cleanUp() will naturally be called within code ‘task’.

block-passing