NSPredicate that is the equivalent of SQL's LIKE

IphoneCocoaCocoa TouchCore DataNspredicate

Iphone Problem Overview


I'm looking for a way to use NSPredicate to set a LIKE condition to fetch objects. In addition to that, an OR would be useful as well. I'm trying to do something where if a user searches "James" I can write an NSPredicate that will do the equivalent of:

select * from users where firstname LIKE '%James%' OR lastname LIKE '%James%';

Iphone Solutions


Solution 1 - Iphone

NSString *_mySearchKey = @"James";
NSPredicate *_myPredicate = [NSPredicate predicateWithFormat:@"(firstname CONTAINS[cd] %@) OR (lastname CONTAINS[cd] %@)", _mySearchKey, _mySearchKey];

Solution 2 - Iphone

The CONTAINS operator will certainly work just fine. If you're looking for a more direct correlation, then 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

Solution 3 - Iphone

Another possibility

@"firstname beginswith[c] James"

As a nice alternative to contains

Sometimes contains isn't always the right answer

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrandombitsView Question on Stackoverflow
Solution 1 - IphoneAlex ReynoldsView Answer on Stackoverflow
Solution 2 - IphoneDave DeLongView Answer on Stackoverflow
Solution 3 - IphoneM. RyanView Answer on Stackoverflow