11.2. Retrieving a Reference to an Address Book

Problem

You would like to work with a user’s contacts. To do this, first you need to get a reference to the user’s address book database. This reference is what you use to retrieve entries, as well as to make and save changes.

Solution

Use the ABAddressBookCreateWithOptions function in the Address Book framework. As the option, pass NULL and pass a reference to an error object to get any errors that may happen during the process:

addressBook = ABAddressBookCreateWithOptions(NULL, &error);

Discussion

To get a reference to the user’s address book database you must first check whether you have permission, as discussed in Recipe 11.1. After permission is granted to your app, you can carry on to use the ABAddressBookCreateWithOptions function. This function returns a value of type ABAddressBookRef that will be nil if the address book cannot be accessed. You must check for nil values before accessing the address book reference returned by this function. Attempting to modify a nil address book will terminate your application with a runtime error.

After retrieving a reference to the user’s address book, you can start making changes to the contacts, reading the entries, and so on. If you have made any changes to the address book, the ABAddressBookHasUnsavedChanges function will tell you by returning the value YES.

Note

An instance of the address book database returned by the ABAddressBookCreate function must be released when you are finished working ...

Get iOS 6 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.