Objective-C is a weird language and it gets weirder with the inclusion of blocks. Blocks can be utilized by any iOS application running iOS 4 or later. In this article we are going to demonstrate how you can utilize blocks in your own application.
Blocks:
You can think of blocks as closures! They encapsulate a portion of code which can then be passed around to different methods and invoked later. This results in writing less code to achieve more. Apple has already started to introduce methods that support blocks.
Below you can see the implementation of the simplest block:
Unfortunately, the above block is not quite useful since it does not provide a name and hence cannot be invoked by other callers. Let’s redefine this block again:
Let’s break down the above code to get a better idea.
In the above code we are defining structure of the block. The block returns void and takes in nothing (void). The name of the block is prefixed with the “^” symbol which represents that this is a block.
The next part is the body of the block which is defined on the right side of the equal to sign:
There is no return type declared since if the block has to return anything then it will return from inside the { } body. You can easily invoke this block as follows:
The body of the block will gets executed and it will print a message to the console “I am a very simple block!”.
Let’s create a block that takes in a single parameter and returns a value.
One thing to notice is that you do not provide a name for your variable when you are declaring a block. You only provide the name when you are defining the block as indicated in the above implementation.
Let’s take this a step further and define a block that takes multiple input parameters.
Passing Blocks to Methods:
The real benefit of using blocks is that you can easily pass them as parameters to methods. In this example we are passing a block to the prepareRequest method.
The first parameter is a simple string which represents the url. The second parameter is a block which takes in the string parameter and returns nothing. The implementation is shown below:
The prepare method can be called using the code below:
The prepare method can be refactored by using typedef to represent the block parameter as shown in the implementation below:
As you can see using typedef cleans up the code and makes things more readable.
Conclusion:
In this article we learned the basics of blocks in iOS development. Apple is moving their latest API’s to blocks implementation and it also seems that more and more third party libraries are exposing their functionalities using blocks.