iphone & Objective C - Filtering an array using NSPredicate?

瘦欲@ 提交于 2019-12-08 09:47:57

问题


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];

回答1:


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.




回答2:


filtering NSArray into a new NSArray in objective-c

That should help



来源:https://stackoverflow.com/questions/3999242/iphone-objective-c-filtering-an-array-using-nspredicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!