iOS - Finding a complex object in an array

cocoa, cocoa-touch, ios, ipad, iphone

Solution

I would recommend `NSPredicate`. You could do it with something like this, assuming `listOfItems` is your array containing your `NSObject`'s with said properties.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"number == 10"];
NSArray *filtered = [listOfItems filteredArrayUsingPredicate:predicate];

Your filtered results, any numbers matching `10` will now be in the `filtered` array. If you want to cast back to your object, you can do something like this:

YourObject *object = (YourObject*)[filtered objectAtIndex:0];

Hope this helps.

Problem

I have an object from a NSObject class that I call "brand" and has the following properties: ``` .name .number .site ``` at a given time, dozens of these objects are stored on a NSMutableArray, something like: ``` object 1 object 2 object 3 object 4 ... ``` I would like to be able to retrieve a given object from the array by its number. Not the index of the object on the array but the number property of the object (get object that has the number property equal to 10, for example). I know that NSArrays have smart methods for retrieving stuff but I don't know them deeply cause I use this rarely. Is there any way to retrieve that object from the array without having to iterate thru all objects on the array and check each object's number property? Can you guys help? thanks.

Original source