Search code examples
iphoneobjective-caddressbook

How to search iPhone address book for specific user name based on variable and not a string


Apple provides the following sample code in their QuickContacts project for how to search the address book for a particular user.

-(void)showPersonViewController
{
 // Fetch the address book 
 ABAddressBookRef addressBook = ABAddressBookCreate();

 // Search for the person named "Appleseed" in the address book
 CFArrayRef people = ABAddressBookCopyPeopleWithName(addressBook, CFSTR("Appleseed"));

 // Display "Appleseed" information if found in the address book 
 if ((people != nil) && (CFArrayGetCount(people) > 0))
 {
  ABRecordRef person = CFArrayGetValueAtIndex(people, 0);
  ABPersonViewController *picker = [[[ABPersonViewController alloc] init] autorelease];
  picker.personViewDelegate = self;
  picker.displayedPerson = person;
  // Allow users to edit the person’s information
  picker.allowsEditing = YES;

  [self.navigationController pushViewController:picker animated:YES];
 }
 else 
 {
  // Show an alert if "Appleseed" is not in Contacts
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" 
              message:@"Could not find Appleseed in the Contacts application" 
                delegate:nil 
             cancelButtonTitle:@"Cancel" 
             otherButtonTitles:nil];
  [alert show];
  [alert release];
 }
 CFRelease(addressBook);
 CFRelease(people);
}

The line that I'm having trouble with is:

// Search for the person named "Appleseed" in the address book
CFArrayRef people = ABAddressBookCopyPeopleWithName(addressBook, CFSTR("Appleseed"));

This will search the address book for the person named "Appleseed", but I want to search the address book based on a user that is stored in a variable. For example, I'm trying:

Customer *customer = [customerArray objectAtIndex:indexPath.row];
cell.textLabel.text = customer.name;

CFArrayRef people = ABAddressBookCopyPeopleWithName(addressBook, CFSTR(customer.name));

The "customer.name" isn't resolving to the value that is stored. I used NSLog to output the value of customer.name and it holds the expected value.

How can I resolve this variable to a string so it will search the address book properly?

Thanks!


Solution

  • Is customer.name an NSString?

    CFSTR only accepts literal C strings.
    To pass an NSString, cast it to CFStringRef:

    CFArrayRef people = ABAddressBookCopyPeopleWithName(addressBook,
                                            (CFStringRef)customer.name);