Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

27. Blocks > Basics of Using Blocks

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 and two methods to the BNRExecutor class.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial