O'Reilly logo

Programming iOS 4 by Matt Neuburg

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

Blocks

A block is an extension to the C language, introduced in Mac OS X 10.6 and available if you’re compiling for iOS 4.0 or later. It’s a way of bundling up some code and handing off that entire bundle as an argument to a C function or Objective-C method. This is similar to what we did at the end of the preceding section, handing off a pointer to a function as an argument, but instead we’re handing off the code itself. The latter has some major advantages over the former, which I’ll discuss in a moment.

As an example, I’ll rewrite the preceding example to use a block instead of a function pointer. Instead of calling sortedArrayUsingFunction:context:, I’ll call sortedArrayUsingComparator:, which takes a block as its parameter. The block is typed like this:

NSComparisonResult (^)(id obj1, id obj2)

That’s similar to the syntax for specifying the type of a pointer to a function, but a caret character is used instead of an asterisk character. So this means a block that takes two id parameters and returns an NSComparisonResult (which is merely an NSInteger, with just the same meaning as in the previous example). We can define the block and hand it off as the argument to sortedArrayUsingComparator: all in a single move, like this:

NSArray* arr2 = [arr sortedArrayUsingComparator: ^(id obj1, id obj2) { NSString* s1 = (NSString*) obj1; NSString* s2 = (NSString*) obj2; NSString* string1end = [s1 substringFromIndex:[s1 length] - 1]; NSString* string2end = [s2 substringFromIndex:[s2 length] - ...

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