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

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -