O'Reilly logo

iOS Programming: The Big Nerd Ranch Guide by Joe Conway, 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

Basics of Using Blocks

Say you wanted an object that could take two numbers, add them together, and then return the result. You could probably write that pretty easily. But what if you now wanted that object to perform subtraction? Then multiplication? Division? You’d end up writing a number of methods for this object.

Instead of writing these methods, we can give this object an instance variable that points at a block. When we want to swap out the operation this object uses, we can construct a block literal that performs the appropriate operation. When the object is asked to compute the result, it executes the operation in the block.

Create a new NSObject subclass for Blocky and name it BNRExecutor. In BNRExecutor.h, add an instance variable ...

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