Hello!
Today we will be learning all about blocks! Blocks are perceived to be extremely hard and complex topics, but after today's tutorial you will hopefully see how much power they can add to your code. Blocks are very versatile. They can not only execute code, but they are also treated as Objective-C objects. So let's dive right in!
Today we will be learning all about blocks! Blocks are perceived to be extremely hard and complex topics, but after today's tutorial you will hopefully see how much power they can add to your code. Blocks are very versatile. They can not only execute code, but they are also treated as Objective-C objects. So let's dive right in!
First download the starter project here.
Blocks
Here we go! Let's open up the starter project, and then navigate to the Blocks.m file. First we will be looking at blocks without any arguments. Here is the basic syntax for blocks.
Using that format let's write our first block without any arguments!
Let's break that down. First we put the name of the block that we declared in the .h file. Then after the equals sign is a ^{ }. In the curly braces is the code that will run when this block is called which is like this.
This is how you declare the block.
It is the same concept as variables. First you declare them in the .h file. Then in the .m file you give it a value. In this case the value of the block is what runs when the block is called. Here is how the finished .m file should look.
Run the code and watch what is outputted!
Now let's look into blocks with arguments. Write out the block.
It is the same syntax as a block with no arguments except for after the equals sign. Instead of just this ^{ }. There is ^(){ }. In between the parentheses are the arguments' names and types. Then in the curly braces is the code that is run when the block is called. Here is how the block is declared.
First the return type is specified. Then the name of the block. Then only the types of the arguments.
This is how you would call the block.
This is how you would call the block.
Run the code! Look at the output!
Nice job! You just completed a very useful feature in Objective-C programming! That finishes our Objective-C basics series! Next I will have a post about where to go from here, and the future of this blog. As always feel free to post any questions, comments, and suggestions down below. Or you can email me at [email protected].
Thank you!
Zachary Cmiel
The PoKoBros
Thank you!
Zachary Cmiel
The PoKoBros