苹果手机和Objective C - 使用 NSPredicate 过滤数组?
我有一个对象数组(用户) 每个用户都有一个名为“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你已经差不多明白了,只是还差一点点。
每个
用户
都有一组设备
。这意味着当您调用[aUser valueForKeyPath:@"devices.category"]
时,它将为您提供设备类别聚合的集合。换句话说,如果您的用户有 2 台设备,并且它们(分别)的
类别
为“移动”和“桌面”,则“devices.category”
将返回(移动设备、桌面设备)
。这是一个向量值。它包含多个元素。但是,您将其与标量值(单个元素)
@"mobile"
进行比较。我认为您想要选择至少拥有一台属于“移动”类别的设备的所有用户,对吗?如果是这种情况,那么您只需使用
ANY
关键字,并按如下方式创建谓词:有关这些聚合函数的更多信息,请查看 谓词编程指南。
You've almost got it, just a little bit off.
Each
User
has a set ofDevices
. 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:For more information on these aggregate functions, check out the Predicate Programming Guide.