1

在我的 iOS 应用程序中,我想找到与姓名匹配的联系人的电话号码。

CFErrorRef *error = NULL;

// Create a address book instance.
ABAddressBookRef addressbook = ABAddressBookCreateWithOptions(NULL, error);

// Get all people's info of the local contacts.
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressbook);
CFIndex numPeople = ABAddressBookGetPersonCount(addressbook);
for (int i=0; i < numPeople; i++) {

    // Get the person of the ith contact.
    ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
    ## how do i compare the name with each person object?
}
4

1 回答 1

0

您可以使用 获取此人的姓名ABRecordCopyCompositeName,并测试搜索字符串是否包含在使用 的姓名中CFStringFind

例如,要查找姓名中带有“Appleseed”的联系人:

CFStringRef contactToFind = CFSTR("Appleseed");

CFErrorRef *error = NULL;

// Create a address book instance.
ABAddressBookRef addressbook = ABAddressBookCreateWithOptions(NULL, error);

// Get all people's info of the local contacts.
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressbook);
CFIndex numPeople = ABAddressBookGetPersonCount(addressbook);
for (int i=0; i < numPeople; i++) {

    // Get the person of the ith contact.
    ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);

    // Get the composite name of the person
    CFStringRef name = ABRecordCopyCompositeName(person);

    // Test if the name contains the contactToFind string
    CFRange range = CFStringFind(name, contactToFind, kCFCompareCaseInsensitive);

    if (range.location != kCFNotFound)
    {
        // Bingo! You found the contact
        CFStringRef message = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("Found: %@"), name);
        CFShow(message);
        CFRelease(message);
    }

    CFRelease(name);
}

CFRelease(allPeople);
CFRelease(addressbook);

希望这可以帮助。尽管您的问题是 5 个月前提出的...

于 2013-08-30T07:45:12.080 回答