I have implemented a UISearchDisplayController that allows users to search a table. Currently the predicate I am using to search is as follows,
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"Name contains[cd] %@", searchText];
Now lets say a users searches for “beans, cooked” the corresponding matches are found in the table. But if the user enters the search text as “beans cooked” without the comma, there will be no matches found.
How can I re-write my predicate to “ignore” the commas when searching? In other words how can I re-write it so that it views “beans, cooked” being equal to “beans cooked” (NO COMMMA)?
First a disclaimer:
I think that what you are trying to do is to add some “fuzzyness” to your search algorithm, seen that you want to make your match insensitive to certain differences in user input.
Predicates (which are logic constructs) are by their very nature not fuzzy, so there is an underlying impedance mismatch between the problem and the tool chosen.
Anyway, one way to go about it could be to add a method to your model object class.
In this method, you can clean your name string so it only contains the most basic characters, say numbers, ascii letters and a space.
Being totally deterministic, such a method is effectively a read-only string property on your object, and as such it can be used to match in predicates.
Here is an implementation that removes punctuation, accents and diacritics:
Now, a predicate could be made to search in the simplified name:
You would of course want to clean the search string using the same algorithm used to clean the name, so it would probably be a good idea to factor it out into a general method to be used in both places.
Last, the
simplifiedNamemethod can also be added by implementing a category to the model object class so you don’t have to modify its code, which is handy in case your object class is defined in an auto-generated file by Core Data.