Using the Address Book C API

For the most part, the Objective-C API has close method and syntax parity with the C API. This makes it easy to determine, for example, which function corresponds to a given Objective-C method.

There are a couple of primary differences that developers need to be aware of when using the Address Book C API:

To access the user’s shared address book using the C programming interface, you need to use the value returned by ABGetSharedAddressBook.

ABAddressBookRef addressBook = ABGetSharedAddressBook();

Compare this with the corresponding code using the Objective-C programming interface, noting the mapping between corresponding method and function names.

ABAddressBook *addressBook = [ABAddressBook sharedAddressBook];

This example from “Searching an Address Book,” Listing 1, searches for anyone named Smith in the current user’s address book and returns an array of results.

Listing 1  A simple search, in Objective-C

ABAddressBook *AB = [ABAddressBook sharedAddressBook];
 
ABSearchElement *nameIsSmith =
    [ABPerson searchElementForProperty:kABLastNameProperty
                                 label:nil
                                   key:nil
                                 value:@"Smith"
                            comparison:kABEqualCaseInsensitive];
 
NSArray *peopleFound =
    [AB recordsMatchingSearchElement:nameIsSmith];

Listing 2 performs the same search using the C API. Again, note the mapping between corresponding method and function names.

Listing 2  A simple search, in C

ABAddressBookRef AB = ABGetSharedAddressBook();
 
ABSearchElementRef nameIsSmith =
    ABPersonCreateSearchElement(kABLastNameProperty,
                    NULL,
                    NULL,
                    CFSTR("Smith"),
                    kABEqualCaseInsensitive);
 
CFArrayRef peopleFound =
    ABCopyArrayOfMatchingRecords(AB, nameIsSmith);

For more details about using the C API for the Address Book framework, refer to Address Book C Framework Reference for Mac.