NSPredicate相当于SQL的LIKE

ran*_*its 50 iphone cocoa cocoa-touch core-data nspredicate

我正在寻找一种方法NSPredicate来设置LIKE条件来获取对象.除此之外,一个OR也是有用的.我正在尝试做一些事情,如果用户搜索"詹姆斯"我可以写一个NSPredicate将做相当于:

select * from users where firstname LIKE '%James%' OR lastname LIKE '%James%';
Run Code Online (Sandbox Code Playgroud)

Ale*_*lds 120

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

  • 找到了!这意味着Case&Diacritic不敏感 (33认同)
  • 什么意思是`[cd]`?我在文档中找不到这个. (2认同)

Dav*_*ong 37

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

NSString *_mySearchKey = @"James";
NSPredicate *_myPredicate = [NSPredicate predicateWithFormat:@"firstname LIKE '*%1$@*' OR lastname LIKE '*%1$@*'", _mySearchKey];
Run Code Online (Sandbox Code Playgroud)

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

  • 使用like的技巧是在参数中包含*标记.ie:`NSPredicate*predicate = [NSPredicate predicateWithFormat:@"%K LIKE [cd]%@",kMDItemDisplayName,[NSString stringWithFormat:@"*%@*",appname]]; (7认同)
  • 我知道这是很久以前的事了,但是这不起作用,因为NSPredicate不会替换引用的内容'%@'将保留'%@'... (6认同)

M. *_*yan 10

另一种可能性

@"firstname beginswith[c] James"
Run Code Online (Sandbox Code Playgroud)

作为包含的一个很好的替代品

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