ios 使用 NSPredicate 用数组搜索数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11292479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using NSPredicate to search an array with an array
提问by quantum
I have an array of Card
objects (NSObjects), each with a field called tags
, which is an NSArray of NSStrings.
我的阵列Card
对象(NSObjects),各自具有被称为字段tags
,这是NSString的的一个NSArray。
I would then like to split up the user's search term into an array called keywords
of strings by componentsSeparatedByString
, then use NSPredicate to filter my array of Cards based on which elements have tags containing at least 1 keyword in keywords
.
我会再像分割用户的搜索术语称为数组keywords
的字符串componentsSeparatedByString
,然后使用NSPredicate来筛选我在此基础上的元素都包含至少1关键字标签卡的阵列keywords
。
I hope that's not too convoluted! I've tried using the NSPredicate IN
clause to no avail. How should I do this?
我希望这不会太复杂!我试过使用 NSPredicateIN
子句无济于事。我该怎么做?
回答by Vignesh
Considering array
contains card Object.
考虑array
包含卡片对象。
NSArray *keyWordsList = [keywords componentSeparatedByString:@","];
[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"ANY %K IN %@",@"tags",keyWordsList]]
EDIT:
编辑:
To search partially you can use LIKE operator.
要部分搜索,您可以使用 LIKE 运算符。
[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"ANY %K LIKE[cd] %@",@"tags",[partialkeyWord stringByAppendingString:@"*"]]]
回答by Paul de Lange
Don't kill me if this isn't exactly right, but something like this will work.
如果这不完全正确,请不要杀我,但这样的事情会起作用。
NSArray* arrayOfCards = [NSArray array];
NSArray* keywords = [NSArray array];
NSPredicate* containsAKeyword = [NSPredicate predicateWithBlock: ^BOOL(id evaluatedObject, NSDictionary *bindings) {
Card* card = (Card*)evaluatedObject;
NSArray* tagArray = card.tags;
for(NSString* tag in tagArray) {
if( [keywords containsObject: tag] )
return YES;
}
return NO;
}];
NSArray* result = [arrayOfCards filteredArrayUsingPredicate: containsAKeyword];