views:

43

answers:

1

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 sharedAddressBook];
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];
}
+4  A: 

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

Peter Hosey
Hi peter, Your logic have removed 1000 contacts in just 5 secs. This is great. Thanks for your answer. By the code that i have posted takes so much time for removing contacts. I needs that for restoring backup from Server. Thanks again.
Hiren Gujarati