Search code examples
iosmemory-managementaddressbook

CFRelease(addressBook) crashes my iOS app


- (void)tableView:(UITableView *)tableView 
accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = indexPath.row;

    if (row == NSNotFound)
        return;

    if (call.uid != kABRecordInvalidID)
    {
        ABAddressBookRef addressBook = ABAddressBookCreate();

        ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook,
                                                                call.uid);


       // CFRelease(addressBook);// commenting out this makes the program not crash

}
}

Here is the issue, static code analysis tells me I have a memory leak because I'm not releasing the address book. I try to release it but if I return to the screen where it was released and call this function again, the app crashes.

So imagine I click on the accessory button on for a uitableview. I do what I have to do and return to the original window, I then click on the accessory button of the uitableview again and the program crashes with this error:

-[Not A Type retain]: message sent to deallocated instance 0x618d810


Solution

  • The address book isn't the thing that's causing the crash (directly).

    You aren't retaining your person, you're just getting a reference to him/her. Try using CFRetain on your person.

    ABAddressBookRef addressBook = ABAddressBookCreate();
    ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook,
                                                            call.uid);
    CFRetain(person);
    CFRelease(addressBook);