O'Reilly logo

Objective-C Programming: The Big Nerd Ranch Guide by Mikey Ward, Aaron Hillegass

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

28 Blocks

A block is a chunk of code. Here is a block:

^​{​
 ​ ​ ​ ​N​S​L​o​g​(​@​"​T​h​i​s​ ​i​s​ ​a​n​ ​i​n​s​t​r​u​c​t​i​o​n​ ​w​i​t​h​i​n​ ​a​ ​b​l​o​c​k​.​"​)​;​
}​

It looks like a C function; it is a set of instructions inside curly braces. It does not, however, have a name. Instead, the caret (^) identifies this bit of code as a block.

Like a function, a block can take arguments and return values. Here is another block:

^​(​d​o​u​b​l​e​ ​d​i​v​i​d​e​n​d​,​ ​d​o​u​b​l​e​ ​d​i​v​i​s​o​r​)​ ​{​
 ​ ​ ​ ​d​o​u​b​l​e​ ​q​u​o​t​i​e​n​t​ ​=​ ​d​i​v​i​d​e​n​d​ ​/​ ​d​i​v​i​s​o​r​;​
 ​ ​ ​ ​r​e​t​u​r​n​ ​q​u​o​t​i​e​n​t​;​
}​

This block takes two doubles as arguments and returns a double.

You can pass a block as an argument ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required