Blocks
A block is an extension to the C language, introduced in Mac OS X 10.6 and available in 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 in Example 3-1, 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 Example 3-1 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 Example 3-1). We can define the block and hand it off as the argument to sortedArrayUsingComparator: all in a single move, as in Example 3-2.
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] ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access