10.2. Retrieving All the People in the Address Book

Problem

You want to retrieve all the contacts in the user’s address book.

Solution

Use the ABAddressBookCopyArrayOfAllPeople function to retrieve an array of all contacts:

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

  ABAddressBookRef addressBook = ABAddressBookCreate();

  if (addressBook != nil){
    NSLog(@"Successfully accessed the address book.");

    NSArray *arrayOfAllPeople = (__bridge_transfer NSArray *)
                                ABAddressBookCopyArrayOfAllPeople(addressBook);

    NSUInteger peopleCounter = 0;
    for (peopleCounter = 0;
         peopleCounter < [arrayOfAllPeople count];
         peopleCounter++){

      ABRecordRef thisPerson =
        (__bridge ABRecordRef)[arrayOfAllPeople objectAtIndex:peopleCounter];

      NSLog(@"%@", thisPerson);

      /* Use the [thisPerson] address book record */

    }

    CFRelease(addressBook);

  }

  self.window = [[UIWindow alloc] initWithFrame:
                 [[UIScreen mainScreen] bounds]];

  self.window.backgroundColor = [UIColor whiteColor];
  [self.window makeKeyAndVisible];
  return YES;
}

Discussion

After accessing the user’s address book database, we can call the ABAddressBookCopyArrayOfAllPeople function to retrieve an array of all the contacts in that address book. The return value of this function is an immutable array of type CFArrayRef. You can’t work with this type of array as you would work with instances of NSArray, but you have two ways to traverse a CFArrayRef array. First, it natively supports two functions:

CFArrayGetCount ...

Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.