0

I am creating Custom phone book. In search bar functionality i need to search specific contact using text entered. so what predicate should i write which will filter Array from Addressbook Array of type ABrecord? it should be something like name begins with "text"

Sambhav
  • 15
  • 5

2 Answers2

0

why you wana use NSPredicate ? ... look at this link if it is helpful!

Badre
  • 710
  • 9
  • 17
  • This link is not opening .. want to use nspredicate for faster search. i have 5000+ contacts – Sambhav Nov 04 '14 at 11:53
  • Judging by the URL, I think this was [the intended link](https://developer.apple.com/library/mac/documentation/UserExperience/Conceptual/AddressBook/Tasks/Searching.html#//apple_ref/doc/uid/20001024-BABHHIHC). Unfortunately, that's for the Mac OS Address Book framework, not the iOS framework (which is different). – Rob Nov 04 '14 at 13:44
0

You could do something like:

NSArray *allPeople = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id person, NSDictionary *bindings) {
    NSString *firstName = CFBridgingRelease(ABRecordCopyValue((__bridge ABRecordRef)person, kABPersonFirstNameProperty));
    if (firstName && [firstName rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == 0)
        return TRUE;

    NSString *lastName = CFBridgingRelease(ABRecordCopyValue((__bridge ABRecordRef)person, kABPersonLastNameProperty));
    if (lastName && [lastName rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == 0)
        return TRUE;

    // repeat for all of the properties you want to search

    return FALSE;
}];
NSArray *searchResults = [allPeople filteredArrayUsingPredicate:predicate];

Note, if doing lots of these searches, and you want to void doing this ABRecordCopyValue inside the block, you can create your own array of custom objects (or dictionaries) with whatever keys you want, thereby doing this ABRecordCopyValue once for all of your fields for all of your records, and then you can use predicateWithFormat on your array of custom objects repeatedly without incurring the overhead of doing ABRecordCopyValue repeatedly. But I don't believe that Apple has ever published keys that one could use with array of ABRecordRef that you can use in conjunction with predicateWithFormat yourself.


If you just wanted to search for the name, you could also use ABAddressBookCopyPeopleWithName, which eliminates the need for the predicate altogether:

NSArray *searchResults = CFBridgingRelease(ABAddressBookCopyPeopleWithName(addressBook, (__bridge CFStringRef)searchTerm));
Rob
  • 415,655
  • 72
  • 787
  • 1,044