Blocks in Objective-C


Blocks in Objective-C

Quick overview

Blocks are the closure pattern implementation in Objective-C. Blocks are objects containing code like a method but blocks are standalone objects (not belonging to a specific class/instance) encapsulating and capturing the code and variables enclosed in the beginning and closing brackets.

You declare a block type or variable this way:
returnType (^blockName)(paramType, paramType)

Assign a block to this variable:
    ^ returnType (paramType paramName, paramType paramName) {
… code …
}

Block as a parameter:
(returnValue (^)(paramType, paramType))blockName

Call with a block as parameter:
^ returnType (paramType paramName, paramType paramName) {
… code …
}

Some example

You declare a block variable the following way:

You can assign a new block to the same variable; you can also avoid the declaration of the return value since the compiler can find it out:

Even you can avoid the parameter declaration so you get the simplest form of a block:

 

Passing blocks as parameters the syntax change a bit