Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate contains search in a string that contains number and letters

I have to use NSPredicatefor search through some Core Data objects. But the key nameof the custom object could contains both numbers then letters. The string could look like:John 1234 Lennonor Ringo Starr. I normally would use the predicate NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Any name CONTAINS[cd] %@",searchString];

But, if I search for John Lennon the predicate don't return anything, because it can't compare if it contains the characters John Lennon, since is missing the 1234. Any tips what kind of predicate I can use?

like image 678
lagos Avatar asked Dec 16 '22 18:12

lagos


1 Answers

You can tokenise your query , maybe as simple as

NSArray *tokens = [querystring componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

Then construct a compound predicate.

NSMutableArray *predarray = [NSMutableArray array];

for(NSString *token in tokens)
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Any name CONTAINS[cd] %@",token];
    [predarray addObject:predicate];
}

NSPredicate *final = [NSCompoundPredicate andPredicateWithSubpredicates:predarray];

And feed that to your query

In real life I would run a bit of validation against each token to check its going to make a valid predicate and wont crash or create a security risk. e.g Strip special chars like "* []"

EDIT:Corrected predicate type to work with questions situation.

like image 182
Warren Burton Avatar answered May 16 '23 07:05

Warren Burton