我正在寻找一种方法来使用NSPredicate
设置LIKE
条件来获取对象。除此之外,OR
也很有用。我试图做一些事情,如果用户搜索“詹姆斯”,我可以写一个NSPredicate
,它将完成相同的操作:
select * from users where firstname LIKE '%James%' OR lastname LIKE '%James%';
答案 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];
答案 2 :(得分:10)
另一种可能性
@"firstname beginswith[c] James"
作为包含
的一个不错的替代品有时包含并不总是正确答案