ios - Implement search similar to native contacts search? -
on native contacts app, when try search contacts, type string , if contact first name / last name / company etc.. begin string, contact shown.
to make matters more complex, can type mi ric , search find michael richardson. ric mi me michael richardson.
i have made copy of contact record local core data store, , first instinct use nsfetchedresultscontroller
, nice predicate.
but how go predicate? if person record has 3 words, should query each word beginswith? can done 1 predicate?
here use word base predicate:
+ (nspredicate *)wordbasedpredicateforstring:(nsstring *)searchstring withproperty:(nsstring *)property { // searchstring = [searchstring stringforsearch]; nsarray *searchstrings = [searchstring componentsseparatedbycharactersinset:[nscharacterset whitespacecharacterset]]; nsmutablearray<nspredicate *> *subpredicates = [nsmutablearray array]; (nsstring *string in searchstrings) if (![string isequaltostring:@""]) { nsstring *mainstring = [property stringbyappendingstring:@" contains[cd] "]; mainstring = [nsstring stringwithformat:@"%@ contains[cd] %%@",property]; nspredicate *predicate = [nspredicate predicatewithformat:mainstring, string]; [subpredicates addobject:predicate]; } if ([searchstring containsstring:@" "] && subpredicates.count > 0) { nsstring *mainstring = [property stringbyappendingstring:@" contains[cd] "]; mainstring = [mainstring stringbyappendingstring:@"' '"]; nspredicate *emptyspacepredicate = [nspredicate predicatewithformat:mainstring, nil]; [subpredicates addobject:emptyspacepredicate]; } nscompoundpredicate *predicate = [nscompoundpredicate andpredicatewithsubpredicates:subpredicates]; return predicate; }
let assume have contact
object name
property
nspredicate *namepredicate = [self wordbasedpredicateforstring:searchstring withproperty: @"name"];
then filter array:
nsarray *results = [contacts filteredarrayusingpredicate:namepredicate];
and of course can make multiple word base predicates name, company, address etc , make 1 compoundpredicate this:
orpredicate = [nscompoundpredicate orpredicatewithsubpredicates:@[namepredicate, addresspredicate, phonepredicate]];
hope ;)
Comments
Post a Comment