1

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

filteredArrayUsingPredicate is certainly what I'm using, but I get an empty array from the first predicate, hence my question. I'll play with it again to ensure I'm not missing something, but the empty array is why I posted the question.
What is the type of latitude? I just ran some predicate tests on an array of objects with a numerical property, and the equivalent of your first predicate worked fine for properties of type float as well as NSNumber.
Despite being 100% certain I was running the predicate against an NSArray, I was instead running it against an NSMutableArray. I'm surprised there was no complaint during the build. Thanks for your help.
@dodo asked what "latitude > 30.0" refers to. In my case the objects in the array have a property named "latitude". My predicate filtered the list to include only objects where the value of the latitude property was greater than 30.0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.