Potential Memory leak abaddressbookcopyarrayofallp

2019-09-19 10:41发布

问题:

This is function to reload my address book after saving changes, the line

self.addressbook=ABAddressbookCreateWithOptions()

and

self.contactAdd=ABAddressBookCopyArrayOfAllPeople(self.addressBook)

are showing as the potential memory leak points.

contactAdd is of type CFArrayRef and address book is ABAddressBookRef

  -(void)reloadAddressBook
    {
    //   if(self.addressBook)
    //       CFRelease(self.addressBook);
       self.addressBook = ABAddressBookCreateWithOptions(NULL,NULL);
        if(ABAddressBookHasUnsavedChanges(self.addressBook))
        {

            ABAddressBookSave(self.addressBook,NULL);
        }
    //    if(self.contactAdd)
    //        CFRelease(self.contactAdd);

        self.contactAdd=ABAddressBookCopyArrayOfAllPeople(self.addressBook);
    }

回答1:

use _addressbook instead of self.addressBook.



回答2:

use another variable to assign like this

contactAddtemp=ABAddressBookCopyArrayOfAllPeople(self.addressBook); 
self.contactAdd=(__bridge_retained CFArrayRef) CFBridgingRelease(contactAddtemp); 

It worked for me in xcode 4.2 but when I checked it doesnt work in 4.6 may be cause it uses ABAddressBookCreateWithOptions(NULL,NULL) instead of ABAddressBookCreate()



回答3:

In Core Foundation, Create and Copy functions return an ownership reference.

You need to balance that out by calling CFRelease on the returned object (the Address Book, the array of people, and anything else you're getting from such functions), or by casting it with __bridge_transfer (or by calling CFBridgingRelease):

self.addressBook = CFBridgingRelease(ABAddressBookCreateWithOptions(…));