Search ABAddressbook iOS SDK

Rabih picture Rabih · Mar 1, 2011 · Viewed 13.2k times · Source

I want to search the iPhone address book for a specific phone number, and then retrieve the contact name. I am currently looping through all contacts and extracting the multivalue properties and comparing against the value. This is taking way too much time. I have read the Apple addressbook guide, and they say:

"accomplish other kinds of searches, use the function ABAddressBookCopyArrayOfAllPeople and then filter the results using the NSArray method filteredArrayUsingPredicate:."

Can anyone give me an example on how to exactly do that?

Thanks.

Answer

Jay picture Jay · Jun 8, 2011

If you want to do a search in the contacts with phone number, then I will tell you one suggestion.

1.Get all contacts

NSArray *thePeoples = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);

2.Create another array(records) from the contacts array(thePeoples),

records:[ record1, record2, ....recordN ]

record: {name:"myContactName", phoneNumber:"1234567890"}

3.Search the mutableArray(records) with predicate.

NSPredicate * myPredicate = [NSPredicate predicateWithFormat:@"record.phoneNumber contains %@",string];

NSArray * filteredArray = [records filteredArrayUsingPredicate:myPredicate];

This is just a simple example to your solution, and remember phoneNumber is a multiValue field. So we will include an array as phone number in the model class variable.