我正在寻找一种使用NSPredicate
设置LIKE
条件以获取对象的方法。除此之外,使用OR
也会很有用。我正在尝试做的是,如果用户搜索“James”,我可以编写一个NSPredicate
,其相当于:
select * from users where firstname LIKE '%James%' OR lastname LIKE '%James%';
我正在寻找一种使用NSPredicate
设置LIKE
条件以获取对象的方法。除此之外,使用OR
也会很有用。我正在尝试做的是,如果用户搜索“James”,我可以编写一个NSPredicate
,其相当于:
select * from users where firstname LIKE '%James%' OR lastname LIKE '%James%';
NSString *_mySearchKey = @"James";
NSPredicate *_myPredicate = [NSPredicate predicateWithFormat:@"(firstname CONTAINS[cd] %@) OR (lastname CONTAINS[cd] %@)", _mySearchKey, _mySearchKey];
CONTAINS
运算符肯定可以很好地工作。 如果您正在寻找更直接的关联,则还可以使用LIKE运算符(*
= 0或多个字符,?
= 1个字符):
NSString *_mySearchKey = @"James";
NSPredicate *_myPredicate = [NSPredicate predicateWithFormat:@"firstname LIKE '*%1$@*' OR lastname LIKE '*%1$@*'", _mySearchKey];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K LIKE[cd] %@", kMDItemDisplayName, [NSString stringWithFormat:@"*%@*", appname]];
- Richard H.%@
两次的情况形成对比;在那种情况下,他需要两次提供 _mySearchKey
。例如:NSLog(@"%1$@ %1$@", @"Hat");
将输出 "Hat Hat"。 - Tommy另一种可能性
@"firstname beginswith[c] James"
作为contains的良好替代选项
有时候,contains并不总是正确的答案