Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - Finding a complex object in an array

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.

like image 864
Duck Avatar asked Jun 16 '12 01:06

Duck


3 Answers

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.

like image 143
skram Avatar answered Oct 14 '22 14:10

skram


NSUInteger indexOfObject10 = [myArray indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
    MyObject *object = (MyObject *)obj;
    return [object.number == 10];
}];

MyObject *object10 = myArray[indexOfObject10];
like image 34
rob mayoff Avatar answered Oct 14 '22 13:10

rob mayoff


I prefer using block extensions to NSArray that let you "talk" to them more naturally and write less code. Something in the lines of the Smalltalk Collections jargon:

  • detect:
  • select:
  • inject:into:
  • etc.

In your case I would use:

MyObject* theObject = [myArray detect:^(MyObject* each){
     return each.number == 10;
}];

Here you have a possible implementation for that extension to NSArray

typedef BOOL (^BlockPredicate) (id element);

-(id) detect:(BlockPredicate) predicateBlock{
     for (id each in self) {
        if (predicateBlock(each)) {
            return each;
        }
    }
    return nil;
}

I find this kind of tools really helpful. I hope you find them useful too.

like image 25
Lio Avatar answered Oct 14 '22 14:10

Lio