New API Using Blocks
Several new C library calls have been introduced using blocks. They have _b appended to their names to indicate they are block calls, similar to the way some library functions have _r appended to indicate re-entrant calls. Some of the more useful ones are:
qsort_b() |
quicksort using a block for a comparator |
bsearch_b() |
binary search using a block for a comparator |
psort_b() |
parallel sort using a block for a comparator |
glob_b() |
generate pathnames matching a pattern, using a block for an error callback |
scandir_b() |
collect pathnames, using blocks for a path selection and comparison |
Cocoa has introduced a large number of block-oriented methods. An easy way to find them all is to search through the framework headers looking for the caret. The caret operator is rarely used in Cocoa header files, so it is a good way to find block methods. Here are some interesting new Cocoa methods:
[array enumerateObjectsUsingBlock: ^(id obj, NSUInteger index, BOOL *stop) { ... }];
You have seen this before. It iterates through the array, invoking a block for each object.
[array enumerateObjectsWithOptions: NSEnumerationReverse | NSEnumerationConcurrent usingBlock: ^(id obj, NSUInteger index, BOOL *stop) { ... }];
You can include some extra options when enumerating an array. Interesting options are NSEnumerationReverse, which iterates through the array backwards, and NSEnumerationConcurrent, which will automatically parallelize the iteration.
[dictionary enumerateKeysAndObjectsUsingBlock: ^(id key, id object, BOOL *stop) { ... }];
This is the fastest way to iterate the keys and values in a dictionary. Fast enumeration over a dictionary only gives you the keys, so getting the corresponding value requires an -objectForKey: call.
NSPredicate *p = [NSPredicate predicateWithBlock: ^BOOL (id obj, NSDictionary *bindings) { ... }];
This creates an NSPredicate that is backed by arbitrary code, which allows you to express more sophisticated predicates than can be constructed using the predicate format language.
Grand Central Dispatch is also heavily block-based and will be covered in Chapter 22: Grand Central Dispatch).