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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:05:33  来源:igfitidea点击:

Using NSPredicate to search an array with an array

objective-ciosnspredicate

提问by quantum

I have an array of Cardobjects (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 keywordsof 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 INclause to no avail. How should I do this?

我希望这不会太复杂!我试过使用 NSPredicateIN子句无济于事。我该怎么做?

回答by Vignesh

Considering arraycontains 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];