开发者

Filtering against properties of objects in an array with a predicate

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?


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜