NSPredicate equivalent to SQL LIKE

I am looking for a way to use NSPredicate to set a LIKE condition to retrieve objects. In addition, it would be useful to use OR . I'm trying to do something, if the user is looking for "James", I can write NSPredicate , which will execute the equivalent:

 select * from users where firstname LIKE '%James%' OR lastname LIKE '%James%'; 
+46
iphone cocoa-touch cocoa core-data nspredicate
Apr 29 2018-10-21T00:
source share
3 answers
 NSString *_mySearchKey = @"James"; NSPredicate *_myPredicate = [NSPredicate predicateWithFormat:@"(firstname CONTAINS[cd] %@) OR (lastname CONTAINS[cd] %@)", _mySearchKey, _mySearchKey]; 
+106
Apr 29 2018-10-29T00:
source share

The CONTAINS statement will certainly work fine. If you are looking for a more direct correlation, you can also use the LIKE operator ( * = 0 or more characters ? = 1 character):

 NSString *_mySearchKey = @"James"; NSPredicate *_myPredicate = [NSPredicate predicateWithFormat:@"firstname LIKE '*%1$@*' OR lastname LIKE '*%1$@*'", _mySearchKey]; 

For reference:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html#//apple_ref/doc/uid/TP40001795-215868

+35
Apr 29 2018-10-22T00:
source share

Another opportunity

 @"firstname beginswith[c] James" 

How a good alternative contains

Sometimes it does not always contain the correct answer

+9
Nov 11 '11 at 14:57
source share



All Articles