NSPredicate that is the equivalent of SQL's LIKE

后端 未结 3 1553
忘了有多久
忘了有多久 2020-12-07 20:21

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

相关标签:
3条回答
  • 2020-12-07 20:39
    NSString *_mySearchKey = @"James";
    NSPredicate *_myPredicate = [NSPredicate predicateWithFormat:@"(firstname CONTAINS[cd] %@) OR (lastname CONTAINS[cd] %@)", _mySearchKey, _mySearchKey];
    
    0 讨论(0)
  • 2020-12-07 21:00

    Another possibility

    @"firstname beginswith[c] James"
    

    As a nice alternative to contains

    Sometimes contains isn't always the right answer

    0 讨论(0)
  • 2020-12-07 21:05

    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

    0 讨论(0)
提交回复
热议问题