这是从iPhone删除联系人的正确方法吗?

时间:2012-05-16 15:36:41

标签: iphone ios5 abaddressbook

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

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

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

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

任何人都可以帮助我。

提前感谢您的帮助。

最高

1 个答案:

答案 0 :(得分:8)

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

CFErrorRef error = nil;

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

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

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

//Creates a pass test block to see if the ABRecord has the same name as delete
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) {
        delete = person;
    }
    return (BOOL) pass;
};

int idx = [peopleArray indexOfObjectPassingTest:predicate];

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

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

使用此代码的一个警告是,它只会删除名称与ABRecord匹配的delete的一个实例。