NSPredicate相当于SQL的LIKE

时间:2010-04-29 21:36:02

标签: iphone cocoa cocoa-touch core-data nspredicate

我正在寻找一种方法来使用NSPredicate设置LIKE条件来获取对象。除此之外,OR也很有用。我试图做一些事情,如果用户搜索“詹姆斯”,我可以写一个NSPredicate,它将完成相同的操作:

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

3 个答案:

答案 0 :(得分:118)

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

答案 1 :(得分:37)

CONTAINS运算符肯定会正常工作。如果您正在寻找更直接的关联,那么您也可以使用LIKE运算符(* = 0或更多字符,? = 1个字符):

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

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

答案 2 :(得分:10)

另一种可能性

@"firstname beginswith[c] James"

作为包含

的一个不错的替代品

有时包含并不总是正确答案