Wednesday, 30 March 2016

Blocks in Objective c

Blocks are Objective c`s anonymous functions . 

Block is a self-contained, autonomous code fragment, existing always in the scope of another programming structure , e.g. body of a method.

Blocks helps you to :
1)  Reduce code
2)  Write more cleaner code
3)  More reliable code

Block basic syntax : 

                        ReturnType (^Name of the block) (Parameters)

  • ReturnType : Any datatype supported by Objective c 

  • ^Name of the block : Name of the block is always preceded by the carret symbol (^).

  • Parameters : Parameters which you want to pass on the block.

Block example : 

Blocks used for array enumeration  :

Arrays enumeration using blocks is fastest .

>> Use this code for faster enumeration of arrays

Blocks Advantages:

1) Blocks can do same as methods but methods can`t do all the tasks like blocks

2) Blocks can be parsed to other functions.

3) Blocks are used in multi-threading

4) Blocks have faster array enumeration as compared to for in and for loops .

5) Blocks are simpler to read.

That`s a small introduction to blocks in objective c. More complex part will be covered in the future tutorials .

Thank you :)