In my iOS application I have a really simple predicate for my fetch controller.
NSString *format = [NSString stringWithFormat:@"name like[c] '%@'", nameVar];
NSPredicate *predicate = [NSPredicate predicateWithFormat:format];
[fetchController setPredicate:predicate];
It performs basic case-insensitive name lookup. Now I’d like to change it so that I could put a number of words in search box (nameVar has the value from search box) separated by spaces and have the predicate filter the results matching all those keywords.
So if I have two names:
“John Smith” and “Mary Smith” and I search for: “Smith M” I would like to have only one result but a search like that: “Sm th ith” should return both values.
Does anyone have an idea how should this be implemented?
edit back on a regular computer…
So there are a couple things to be aware of:
NSExpressionandNSPredicate(specificallyNSComparisonPredicateandNSCompoundPredicate) objects. Your string will be placed into anNSExpressionof typeNSConstantValueExpressionType, meaning that it’s already going to be interpreted as a regular string. Placing the single quotes in the format string will, in fact, make your predicate non-functional.nameVar). In that case, we’ll break thenameVarup into its constituent words, and create a comparison for each word. Once we’ve done that, weANDthem together to create a single overarching predicate. The code below does exactly that.original answer
You can do this by building your own
NSCompoundPredicate:Warning: typed in a browser on my iPhone.