2010-04-29 35 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