2010-04-29 37 views
47

我正在寻找一种方法来使用NSPredicate设置LIKE条件来获取对象。除此之外,OR也是有用的。我试图做一些事情,其中​​如果用户搜索“詹姆斯”我可以写一个NSPredicate,会做等价的:NSPredicate,相当于SQL的LIKE

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

回答

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

什么意思是'[cd]'?我无法在文档中找到它。 – 2013-02-27 12:42:04

+26

找到了!这意味着Case&Diacritic不敏感 – 2013-02-27 13:48:20

+1

@AlexReynolds你为什么不使用LIKE? – onmyway133 2014-04-10 14:54:06

35

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

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

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

+6

我知道这是很久以前,但这是行不通的,因为NSPredicate不会替代引用的内容'%@'将保留'%@'... – 2011-04-03 10:33:29

+1

开始[c]对我来说,但仍然,已任何设法生成动态LIKE查询的人,如'%@ *' – 2012-10-26 15:45:19

+7

使用like的诀窍是在参数中包含*标记。即:'NSPredicate * predicate = [NSPredicate predicateWithFormat:@“%K LIKE [cd]%@”,kMDItemDisplayName,[NSString stringWithFormat:@“*%@ *”,appname]];' – 2013-11-26 02:22:26

9

另一种可能性

@"firstname beginswith[c] James" 

作为一个不错的选择,包含

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

+1

不符合“SuperJames”:)开头并不等于sql的'%foo%' – marsbear 2016-04-30 21:11:22