Display All First And Last Names In The Address Book

This tips demonstrates how to print the first and last names for all entries in the iPhone Address Book to the console. Start by including the following import statement:

#import <addressbook /AddressBook.h>

Also, add the AddressBook.framework to your project.

To display all the address book names, create an address book reference, copy all entries into an array and for each entry, access the first and last name properties.

ABAddressBookRef addressBook = ABAddressBookCreate();
// Can we find the address book...
if (addressBook != nil)
  // Get an array address book entries
  CFArrayRef arrayOfEntries = ABAddressBookCopyArrayOfAllPeople(addressBook);
  // Are there entries in the array?
  if (CFArrayGetCount(arrayOfEntries) > 0)
    CFIndex countOfEntries = CFArrayGetCount(arrayOfEntries);
    NSLog(@"Address book entries: %ld", countOfEntries);
    for (int x = 0; x < countOfEntries ; x++)
      // Get the current entry
      ABRecordRef activeRecord = CFArrayGetValueAtIndex(arrayOfEntries, x);
      // Print first name
      NSString *firstname = (NSString *) ABRecordCopyValue(activeRecord, kABPersonFirstNameProperty);
      NSLog(@"First name: %@", firstname);
      [firstname release];
      // Print last name        
      NSString *lastname = (NSString *) ABRecordCopyValue(activeRecord, kABPersonLastNameProperty);
      NSLog(@"Last name: %@", lastname);
      [lastname release];