Thursday, September 19, 2013

Objective C - Demystifying blocks

Hello guys!

Today we will show you a little bit about Objective C blocks! So if you are learning the language and still confused about blocks, it's time to definitely learn it. According to Apple's Developer Guides, a block is a structure "which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values". What the hell does it mean? Let's try to clarify things until the end of this post.

Imagine that you could mmanipulate a function on the same way you do with variables. It may sound weird for you if you have never used Functional Programming or Ruby Procs and lambdas. But blocks do exactly this - you can pass functions as arguments or return functions. To keep things simple, let's think initially about variables. You can declare a variable in Objective C like this:

The code above declares the variable 'number' and on the sequence attributes the value '22' to it. Cool, you might get used to that. Now let's apply the same logic for a function. First, look how beautiful and pleasant the syntax is:

 double(^myBlock)(double a, double b) = ^(double a, double b)  
   double number = a + b;   
   return number;  

Weird, huh? Let's look at this under another perspective:

Does it look more simple now?
Let's analyse the code above. First, we have the block declaration, that contains a type - 'double' (such as variables) and a name - 'myBlock' (such as variables too). But when we talk about blocks, we are talking about "functions as variables". Functions must have a signature. The return type is specified with the type of the block. The function has two arguments - 'double a' and 'double b'.

On the sequence, after the declaration, we make an attribution to myBlock. Such as a variable, the name comes on the left, then the '=' symbol, then the body of the function. Ignore ^(double a, double b) and you will see a function!

Awesome, isn't it? Of course, the function needs parameters, that's why we have the at '^(double a, double b)'. The '^' is responsible to mark the definition as a block! Remember - this is not a normal function like the ones you declare in your classes ;)

This is it! The basics about Objective C blocks! On a further post, I'll show you some syntax variants and when blocks are our should be used! Hope you could have understood blocks if you had not got it's main idea yet!

Some extra nice references here and here.

No comments:

Post a Comment