如何基于变量而不是字符串搜索iPhone通讯簿中的特定用户名

如何基于变量而不是字符串搜索iPhone通讯簿中的特定用户名,iphone,objective-c,addressbook,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 =

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);
}
我遇到的问题是:

// Search for the person named "Appleseed" in the address book
CFArrayRef people = ABAddressBookCopyPeopleWithName(addressBook, CFSTR("Appleseed"));
这将在地址簿中搜索名为“applesed”的人,但我希望根据存储在变量中的用户搜索地址簿。例如,我正在尝试:

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

CFArrayRef people = ABAddressBookCopyPeopleWithName(addressBook, CFSTR(customer.name));
“customer.name”未解析为存储的值。我使用NSLog输出customer.name的值,它保存预期值

如何将此变量解析为字符串,以便它正确搜索通讯簿


谢谢

customer.name是NSString吗

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

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

只有当有人有同样的问题时,才可以使用
ABAddressBookCopyPeopleWithName
在iOS simulator中找到联系人,除非你重命名他们,否则他们不知何故会被破坏。如果您想测试、同步facebook或类似的联系人,customer是一个数组,我是否可以将“customer.name”转换为一个数组,类似于您将其显示为NSString的方式?根据您的代码示例,customerArray(不是customer)是一个customer对象数组,customer是customer类型的对象,名称是Customer对象中的一个属性。“名称”似乎是NSString类型,因为您正在将其分配给cell.textLabel.text。在任何情况下,都需要向该地址簿方法传递一个CFStringRef。CFStringRef指向一个字符串,而不是数组。谢谢,这有助于澄清问题。然而,当我尝试将customer.name转换为CFStringRef时,当它点击该行时,我在控制台中得到“EXC_BAD_ACCESS”。有什么想法吗?演示如何在Customer.h文件中定义name属性。我假设您正在CellForRowatineXpath中执行此操作。确保任何行的customer不是nil,或任何行的customer.name不是nil。