使用谓词过滤数组中对象的属性

发布于 2024-10-06 09:29:30 字数 784 浏览 0 评论 0原文

我有一个对象数组,我想使用谓词来过滤它们,但我无法弄清楚语法(或者是否不可能)。

假设该对象是位置,它具有纬度经度属性。我有一个名为 allLocations 的数组,我想生成一个新的位置数组,其中纬度属性大于 30。

在获取托管对象时,您可以简单地使用属性名称,但不能使用所以对于数组:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"latitude > 30.0"];

返回没有匹配项(尽管有很多纬度> 30.0的位置对象。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.latitude > 30.0"];

也不好,而

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"[SELF latitude] > 30.0"];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"[location latitude] > 30.0"];

抛出异常。

我运气不好吗?

I have an array of objects that I'd like to filter using a predicate, but I've not been able to figure out the syntax (or whether it's impossible).

Let's say the object is location and it has properties of latitude and longitude. I've got an array of these called allLocations and I want to produce a new array of locations where the latitude property is greater than 30.

When fetching managed objects you can simply use the property name, but not so with arrays:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"latitude > 30.0"];

returns no matches (despite there being plenty of location objects with latitudes > 30.0.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.latitude > 30.0"];

is no good either, while

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"[SELF latitude] > 30.0"];

and

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"[location latitude] > 30.0"];

throw exceptions.

Am I out of luck?

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

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

发布评论

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

评论(1

披肩女神 2024-10-13 09:29:30

您正在寻找的是 NSArray 的 filteredArrayUsingPredicate: 方法。当您将上面的第一个谓词尝试传递给该方法时,它会正常工作。

值得注意的是,NSMutableArray 使用不同的方法来实现类似的效果,filterUsingPredicate:。 MutableArray 版本改变接收者,而 Array 版本返回一个新的数组。

参考:
NSArray类参考
NSMutableArray 类参考

What you're looking for is the filteredArrayUsingPredicate: method of NSArray. Your first predicate attempt above will work fine when you pass it to that method.

It's worth noting that NSMutableArray uses a different method to achieve a similar effect, filterUsingPredicate:. The MutableArray version alters the receiver, whereas the Array version returns a new Array.

Reference:
NSArray Class Reference
NSMutableArray Class Reference

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