0

I am trying to get all the phone number from the Phone Book of iPhone. But my app crashes as soon as I try to fetch the number using kABPersonPhoneProperty. The code snippet is here

ABAddressBookRef addressBook = ABAddressBookCreate(); 
NSMutableArray *allPeople = (NSMutableArray*)ABAddressBookCopyArrayOfAllPeople(addressBook); 
int nPeople = ABAddressBookGetPersonCount(addressBook); 
CFRelease(addressBook);

for(int i=0; i < nPeople; i++ ){

    ABRecordRef person = [allPeople objectAtIndex:i];
    NSString *name = @"";
    CFTypeRef fName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
    CFTypeRef lName = ABRecordCopyValue(person, kABPersonLastNameProperty);
    ABMultiValueRef multi = ABRecordCopyValue(person , kABPersonPhoneProperty);
    NSString *number = (NSString *)ABMultiValueCopyValueAtIndex(multi, 0);

    if ([number length] > 0) {
        if(fName != NULL)
        {
            if (lName != NULL) {
                name = [[NSString stringWithFormat:@"%@", fName] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            }
            else {
                name = [[NSString stringWithFormat:@"%@", fName] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            }
            NSLog(@"Number==>%@ ",number);
        }
    }
    if (fName != NULL) {
        CFRelease(fName);
    }
    if (lName != NULL) {
        CFRelease(lName);
    }
    if (multi != NULL) {
        CFRelease(multi);
    }
}

[allPeople release];

I am unable to figure out the error in this. I am also releasing everything even then it is not running smoothly.

I am even getting potential memory leak when running build and analyze for the code part

ABMultiValueRef multi = ABRecordCopyValue(person , kABPersonPhoneProperty);
    NSLog(@"Number===>%d" , ABMultiValueGetCount(multi));

Please help me out to come.

Any kind of help would be highly appreciated.

Thanks in advance

devsri
  • 6,173
  • 5
  • 32
  • 40

1 Answers1

0

Thanks for the response. I have figured out the solution fot the problem here. I did not release number variable thinking that the reference was passed as reference but it is copied to the returned location, hence need to release number after the usage.

thanks again for all the responses!!

devsri
  • 6,173
  • 5
  • 32
  • 40