Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
This chapter is from the book

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:


quicksort using a block for a comparator


binary search using a block for a comparator


parallel sort using a block for a comparator


generate pathnames matching a pattern, using a block for an error callback


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
           ^(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).

  • + Share This
  • 🔖 Save To Your Account