苹果手机和Objective C - 使用 NSPredicate 过滤数组?

发布于 2024-09-28 19:10:42 字数 262 浏览 3 评论 0原文

我有一个对象数组(用户) 每个用户都有一个名为“devices”的 nsset 是否可以进行过滤,以便数组返回拥有特定名称设备的所有用户。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"devices.category==%@", @"mobile"];
myArray = [allUsersArray filteredArrayUsingPredicate:predicate];

I have an array of objects (Users)
each user has an nsset named "devices"
Is it possible to filter so the array returns all users who have a device with a specific name.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"devices.category==%@", @"mobile"];
myArray = [allUsersArray filteredArrayUsingPredicate:predicate];

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

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

发布评论

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

评论(1

别念他 2024-10-05 19:10:42

你已经差不多明白了,只是还差一点点。

每个用户都有一组设备。这意味着当您调用[aUser valueForKeyPath:@"devices.category"]时,它将为您提供设备类别聚合的集合

换句话说,如果您的用户有 2 台设备,并且它们(分别)的类别为“移动”和“桌面”,则 “devices.category” 将返回(移动设备、桌面设备)。这是一个向量值。它包含多个元素。

但是,您将其与标量值(单个元素)@"mobile" 进行比较。

我认为您想要选择至少拥有一台属于“移动”类别的设备的所有用户,对吗?如果是这种情况,那么您只需使用 ANY 关键字,并按如下方式创建谓词:

[NSPredicate predicateWithFormat:@"ANY devices.category = %@", @"mobile"]

有关这些聚合函数的更多信息,请查看 谓词编程指南

You've almost got it, just a little bit off.

Each User has a set of Devices. This means that when you invoke [aUser valueForKeyPath:@"devices.category"], it's going to give you a collection of the aggregation of the devices' categories.

In other words, if your user has 2 devices, and they (respectively) have a category of "mobile" and "desktop", then "devices.category" will return (mobile, desktop). This is a vector value. It contains multiple elements.

However, you're comparing this to a scalar value (a single element), @"mobile".

What I think you're going for is wanting to select all users that have at least one device that's in the "mobile" category, correct? If that's the case, then you just need to use the ANY keyword, and make your predicate thusly:

[NSPredicate predicateWithFormat:@"ANY devices.category = %@", @"mobile"]

For more information on these aggregate functions, check out the Predicate Programming Guide.

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