如何根据变量而不是字符串搜索iPhone地址簿中的特定用户名

sco*_*ang 2 iphone objective-c addressbook

Apple在其QuickContacts项目中提供了以下示例代码,以了解如何搜索特定用户的通讯簿.

-(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);
}
Run Code Online (Sandbox Code Playgroud)

我遇到麻烦的是:

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

这将在地址簿中搜索名为"Appleseed"的人,但我想根据存储在变量中的用户搜索地址簿.例如,我正在尝试:

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

CFArrayRef people = ABAddressBookCopyPeopleWithName(addressBook, CFSTR(customer.name));
Run Code Online (Sandbox Code Playgroud)

"customer.name"未解析为存储的值.我使用NSLog输出customer.name的值,它保持预期值.

如何将此变量解析为字符串,以便正确搜索地址簿?

谢谢!

小智 5

customer.name是NSString吗?

CFSTR只接受文字C字符串.
要传递NSString,请将其强制转换为CFStringRef:

CFArrayRef people = ABAddressBookCopyPeopleWithName(addressBook,
                                        (CFStringRef)customer.name);
Run Code Online (Sandbox Code Playgroud)