Search code examples
iosiphoneexc-bad-accessaddressbook

Getting EXC_BAD_ACCESS on ABAddressBookSave


I am using below code to remove the contact from my addressbook. (on iOS 5.0). But its giving me EXC_BAD_ACCESS every time on ABAddressBookSave(addressBook, NULL);. I have selected NSZombieEnalbeld but it's still not giving me clear error.

ABAddressBookRef addressBook = ABAddressBookCreate();
 CFErrorRef error = NULL;

 ABRecordRef person = ABAddressBookCopyArrayOfAllSources(addressBook);

 BOOL success = ABAddressBookRemoveRecord(addressBook, person, &error);

 if (success)
 {
     BOOL su = ABAddressBookSave(addressBook, NULL);
     NSLog(@"Removed ----");
 }
 CFRelease(addressBook);

What is going wrong?


Solution

  • The problem is with this line:

    ABRecordRef person = ABAddressBookCopyArrayOfAllSources(addressBook);
    

    ABAddressBookCopyArrayOfAllSources returns an CFArray and not an ABRecord

    If you want to remove a person from the address book, you need to get it's reference like:

    ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook, recordID);
    

    where recordID, the id of the person you are trying to remove (you need to obtain this).

    As for more information on how to get a person from the address book, you can take a look at this SO response