NSPredicate contains a search in a string containing numbers and letters

I need to use NSPredicate to search for some Core Data objects. But the name key of a custom object can contain both numbers and then letters. The line might look like this: John 1234 Lennon or Ringo Starr . I usually used the predicate NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Any name CONTAINS[cd] %@",searchString];

But, if I search for John Lennon , the predicate returns nothing, because it cannot match if it contains John Lennon characters, since 1234 missing. Any hints, which predicate can I use?

+4
source share
3 answers

You can fake your request, perhaps as simple as

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

Then we 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 send it to your request

In real life, I will conduct several checks against each token to check its ability to make a valid predicate and not crash or create a security risk. for example Use special characters like "* []"

EDIT . The type of predicate for working with a situation has been fixed.

+12
source

Try using LIKE instead of contains, and then you can use wild cards, for example John * Lennon should match a line that starts with John and ends with Lennon with any number of other characters in between. You can use? Instead, there will only be one character for each question mark, if you want more control over what corresponded.

0
source

You can split the search string into an array of strings, and then switch your predicate to find any string in the name:

 NSArray *strings = [searchString componentsSeparatedByString:@" "]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"ANY %@ IN name",strings]; 
0
source

Source: https://habr.com/ru/post/1439853/


All Articles