2

我正在尝试从我创建的 iPhone 中删除联系人。我试图找到删除联系人的一个很好的工作示例,但没有找到。添加联系人似乎很容易,但删除联系人似乎很难。以下代码不起作用,但似乎是合理的:

ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordRef delete = ABPersonCreate();

ABRecordSetValue(delete, kABPersonFirstNameProperty, @"Max", nil);
ABRecordSetValue(delete, kABPersonLastNameProperty, @"Mustermann", nil); 

ABAddressBookRemoveRecord(addressBook, delete, &error);
ABAddressBookSave(addressBook, &error);

谁能帮帮我。

在此先感谢您的帮助。

最大限度

4

1 回答 1

8

问题是您正在创建一个ABRecord不在通讯簿中的地址。ABRedord您需要做的是从 .s 中搜索 s数组ABAddressBook。我写了如何为你做到这一点:

CFErrorRef error = nil;

ABAddressBookRef addressBook = ABAddressBookCreate();
__block ABRecordRef toDelete = ABPersonCreate();

ABRecordSetValue(toDelete, kABPersonFirstNameProperty, @"Max", nil);
ABRecordSetValue(toDelete, kABPersonLastNameProperty, @"Mustermann", nil);

// Gets the array of everybody in the address book
NSArray *peopleArray = (__bridge NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);

// Creates a test predicate to see if the ABRecord has the same name as toDelete
BOOL (^predicate)(id obj, NSUInteger idx, BOOL *stop) = ^(id obj, NSUInteger idx, BOOL *stop) {
    ABRecordRef person = (__bridge ABRecordRef)obj;
    CFComparisonResult result =  ABPersonComparePeopleByName(person, delete, kABPersonSortByLastName);
    bool pass = (result == kCFCompareEqualTo);
    if (pass) {
        toDelete = person;
    }
    return (BOOL) pass;
};

int idx = [peopleArray indexOfObjectPassingTest:predicate];

bool removed = ABAddressBookRemoveRecord(addressBook, toDelete, &error);
bool saved = ABAddressBookSave(addressBook, &error);

您可以ABRecord通过更改块代码来更改比较实例的方式。它现在所做的只是比较联系人的姓名。

这段代码需要注意的是,它只会删除一个ABRecord名称与delete's 匹配的 s 实例。

于 2012-05-16T21:44:08.723 回答