使用NSPredicate过滤大型NSArray [英] Filtering a large NSArray with NSPredicate

查看:82
本文介绍了使用NSPredicate过滤大型NSArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含170k个字符串(字典中的单词)和一个字符串,看起来像glapplega的数组。我试图从字符串中提取单词apple(apple是数组中的一个单词)。我还需要确保提取的字是至少3个字符。现在的代码如下:

I have an array containing 170k strings (words in a dictionary), and a string, looking something like "glapplega". I'm trying to extract the word "apple" from the string (with "apple" being a word in the array). I also need to make sure that the extracted word is at least 3 characters. The code I have right now is the following:

NSPredicate *wordPredicate = [NSPredicate predicateWithFormat:@"'%@' contains[cd] SELF", string];
NSPredicate *lengthPredicate = [NSPredicate predicateWithFormat:@"SELF.length > 2"];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[wordPredicate, lengthPredicate]];
return [_words filteredArrayUsingPredicate:lengthPredicate];

长度谓词对它自己起作用,但词谓词不会(它返回一个空数组,尽管apple是数组中的一个字)。

The length predicate works on it's own, but the word predicate does not (it returns an empty array, despite "apple" being a word in the array).

我怀疑在谓词中使用SELF作为右表达式可能有问题,因为所有的例子我发现有它作为左表达式,虽然我没有办法证实这一点。

I suspect that there might be a problem with using SELF as the right expression in the predicate, as all the examples I found have it as the left expression, although I have no way of confirming this.

编辑:我知道这可能使用正则表达式完成(如此处所述),但是希望这会有一个方法,因为正则表达式可以慢这样一个大的数据集。

Edit: I'm aware that this can likely be accomplished with regexs (as described here), but was hoping there would be a way around this, as regexs can be slow with such a large dataset.

推荐答案

解决这个问题很容易如果你使用块谓词自己迭代数组。在某个时候,一个格式化的NSPredicate将不得不归结到这一点,所以不应该有很多的性能命中。 - [NSString rangeOfString:] 可用于测试是否包含字符串。

Solving this problem is easy if you iterate the array yourself using a block predicate. At some point a formatted NSPredicate would have to boil down to this, so there shouldn't be much of a performance hit. -[NSString rangeOfString:] can be used to test for inclusion of the string.

return [_words filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL (id evaluatedString, NSDictionary *bindings) {
    return string.length > 2 && [string rangeOfString:evaluatedString].location != NSNotFound;
}]];

这篇关于使用NSPredicate过滤大型NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆