Objective-C Gets Blocks!

New to Objective-C is the block syntax. A block is a section of code that is grouped together and designed to be treated like one statement. Blocks also package up the lexical scope of variables and functions within its environment. Blocks are found in many languages including, but not limited to, Ruby, Javascript and Lisp. Blocks are objects and should be treated like such!

Programming Language Code Example Colloquial
[1, 2, 3, 4].each do |i|
    puts i
((lambda (a b) (+ b a)) 1 2)
Lambda function
var foo = function () {
   var j = 42;
Anonymous Function, Closure
   return [num1 isEqualToNumber:num2];

Now there are other block structured languages out there but the few listed here are used to provide a basis for understanding if you’re coming from another language where you may have experienced this concept.

Objective-C inherited blocks from the C language, which it is a superset of. Apple has created an extension of the C language implementing blocks. Syntactically, blocks start with the carrot symbol, followed by its return type followed by arguments (enclosed by parenthesis) and finishing off with the code body defined between curly braces.

^Return Type (Arguments) {Code Body}

The blocks return type and arguments are both optional parameters, leaving them off will not effect the block.

^{Code Body}

You can pass blocks to a function:

Repeat(12, ^{
   [str appendFormat:@"rand: %d", rand()];

Scoped variables (by default) are immutable in blocks. To make these mutable you prefix the keyword __block.

For example

__block int count = 0; //mutable thanks to the __block keyword
int specialValue = 50;  //immutable inside the block
  // do some calculation
   int newValue = someCalculatedValue + specialValue;
   count++; //increment the count every time we do this calculation

A good example of when you might want to use a block may be a callback. Since callbacks are generally a grouping of code that will run after an operation.

Post a Comment

Your email is never shared. Required fields are marked *