帮助创建与filteredArrayUsingPredicate一起使用的谓词

发布于 2024-09-06 03:15:50 字数 830 浏览 3 评论 0原文

我正在尝试学习如何使用谓词,因此正在尝试将以下工作代码替换为filteredArrayUsingPredicate...

[filteredLocations removeAllObjects];
for (NSString *location in locations) {
  NSRange range = [location rangeOfString:query options:NSCaseInsensitiveSearch];
if (range.length > 0) {
      [filteredLocations addObject:location];
   }
  }

相反,我正在尝试...

[filteredLocations removeAllObjects];
NSPredicate *predicate =  [NSPredicate predicateWithFormat:@"SELF contains %@", searchText]; 
[filteredLocations addObjectsFromArray: [locations filteredArrayUsingPredicate:predicate]];

我没有得到与for循环rangeOfString相同的谓词结果。例如,对于字符串范围,searchText 返回一个包含 8 项的数组,而对于相同的值,使用谓词仅返回 2 项。另一个例子,hono 会在位置数组中找到 honolulu,但使用谓词不会找到任何内容。

据我了解,SELF 代表正在评估的对象对象,即。位置数组,所以我认为这是正确的语法。

任何帮助将不胜感激,

谢谢,约翰

I am trying to learn how to use predicates and so am trying to replace the following working code with 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.

As I understand it SELF represents the object object being evaluated ie. the locations array, so I think that is the correct syntax.

Any help would be appreciated

Thanks, John

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夕嗳→ 2024-09-13 03:15:51

我认为在您的 for 循环中,您指定了一个选项 NSCaseInsensitiveSearch 但在谓词中您没有指定。

您可以尝试使用这个

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SELF contains[cd] %@)", searchText];

更多详细信息可以在此处查看
NSPredicate 教程

I thought that in your for loop, you specify an option NSCaseInsensitiveSearch but in the predicate you didn't.

You can try with this one

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SELF contains[cd] %@)", searchText];

More details can be looked at here
NSPredicate Tutorial

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文