Search code examples
iphoneiosabaddressbook

Memory leak ABAdressbook


I am getting memory leaks in the following method :

- (void) SyncContactData
{
    ABAddressBookRef addressBook = ABAddressBookCreate();
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
    CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);

    for( int i = 0 ; i < nPeople ; i++ )
    {
        //dicContact = [[NSMutableDictionary alloc] init];

        ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, i );
        NSString *str = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
        NSString *strSub = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
        int ii = [[NSString stringWithFormat:@"%@",strSub] length];
        if(str != nil || ii == 0)
            [arrNames addObject:strSub];
        else
            [arrNames addObject:@""];

        CFTypeRef multival = ABRecordCopyValue(ref, kABPersonPhoneProperty);
        NSArray *arrayPh = (NSArray *)ABMultiValueCopyArrayOfAllValues(multival);
        if([arrayPh count] > 0)
            [arrPhone addObject:[arrayPh objectAtIndex:0]];
        else
            [arrPhone addObject:@""];

        CFRelease(multival);

    }

    CFRelease(addressBook);
    CFRelease(allPeople);

}

Getting leaks here:

  1. NSString *str = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
  2. NSString *strSub = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
  3. NSArray *arrayPh = (NSArray *)ABMultiValueCopyArrayOfAllValues(multival);

Solution

  • You need to release objects that are originally copied when you are done with them:

    [str release];
    [strSub release];
    [arrayPh release];
    

    If ARC is enabled, you might need to use CFRelease instead (and cast appropriately).