xcode 帮助创建一个谓词,用于filteredArrayUsingPredicate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3031111/
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
Help creating a predicate for use with filteredArrayUsingPredicate
提问by user278859
I am trying to learn how to use predicates and so am trying to replace the following working code with filteredArrayUsingPredicate...
我正在尝试学习如何使用谓词,因此我试图用filteredArrayUsingPredicate 替换以下工作代码...
[filteredLocations removeAllObjects];
for (NSString *location in locations) {
NSRange range = [location rangeOfString:query options:NSCaseInsensitiveSearch];
if (range.length > 0) {
[filteredLocations addObject:location];
}
}
Instead I am trying....
相反,我正在尝试......
[filteredLocations removeAllObjects];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains %@", searchText];
[filteredLocations addObjectsFromArray: [locations filteredArrayUsingPredicate:predicate]];
I am not getting the same results with the predicate as I am with for loop rangeOfString. With the range of string for example searchText returns an 8 item array while with the same value returns only 2 with the predicate. Another example, hono will find honolulu in the locations array while it will not find anything using the predicate.
谓词的结果与 for 循环 rangeOfString 的结果不同。例如,对于字符串范围,searchText 返回一个 8 项数组,而具有相同值的谓词仅返回 2。另一个例子,hono 会在locations 数组中找到honolulu,而使用谓词却找不到任何东西。
As I understand it SELF represents the object object being evaluated ie. the locations array, so I think that is the correct syntax.
据我了解,SELF 表示正在评估的对象对象,即。位置数组,所以我认为这是正确的语法。
Any help would be appreciated
任何帮助,将不胜感激
Thanks, John
谢谢,约翰
回答by vodkhang
I thought that in your for loop, you specify an option NSCaseInsensitiveSearch but in the predicate you didn't.
我认为在你的 for 循环中,你指定了一个选项 NSCaseInsensitiveSearch 但在你没有的谓词中。
You can try with this one
你可以试试这个
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SELF contains[cd] %@)", searchText];
More details can be looked at here NSPredicate Tutorial
更多细节可以看这里 NSPredicate 教程