Is this the right way to delete a contact from the iPhone?

六眼飞鱼酱① 提交于 2019-12-03 21:58:42

The problem is that you're creating an ABRecord that isn't inside of the address book. What you have to do is search through an array of ABRedords from the ABAddressBook. I wrote how to do this for you:

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);

You can change how you want to compare ABRecord instances by changing the block code. All it's doing now is comparing the names of the contacts.

A caveat with this code is that it will only delete one instance of the ABRecords whose name matches delete’s.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!