开发者

How to remove all contacts from AddressBook efficiently using the AddressBook framework?

开发者 https://www.devze.com 2023-01-03 23:54 出处:网络
I have written code as below for removing all contacts from addressbook. But it works very slow for more then 1000 contacts. is there any other way for removing all contacts from addressbook. I needs

I have written code as below for removing all contacts from addressbook. But it works very slow for more then 1000 contacts. is there any other way for removing all contacts from addressbook. I needs that for restoring backup in my application.

-(void)removeAllData
{   
ABAddressBook *book = [ABAddressBook sharedAddressB开发者_运维问答ook];
int count = [[book people] count];

for(int i=count;i>=0;i--)
{

    if(i<[[book people] count])
    {
        [book removeRecord:[[book people] objectAtIndex:i]];
    }

}

[book save];
}


You could start by only retrieving the book's people once for the whole loop instead of twice per iteration, and further improve this by looping directly on the array using fast enumeration instead of accessing objects by index:

NSArray *people = [book people];
for (ABPerson *person in people)
    [book removeRecord:person];
[book save];

You also should profile your app in Instruments to see what else might be taking up significant portions of your time. I predict—but you should confirm this yourself—that if you profile your current code, [book people] will show up as a hot spot because you're calling it so much (2000 times when count == 1000).

(I'm assuming you have a good reason to be emptying out the Address Book…)


ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);

int peopleCount = CFArrayGetCount(allPeople);
CFErrorRef *error = nil;
for (int i = 0; i < peopleCount; i++){
    ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
    error = nil;
    ABAddressBookRemoveRecord(addressBook, person, error);
}
error = nil;
ABAddressBookSave(addressBook, error);

CFRelease(allPeople);
CFRelease(addressBook);
0

精彩评论

暂无评论...
验证码 换一张
取 消