开发者

iphone & Objective C - Filtering an array using NSPredicate?

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 predicateWithForm开发者_开发技巧at:@"devices.category==%@", @"mobile"];
myArray = [allUsersArray filteredArrayUsingPredicate:predicate];


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜