Search code examples
objective-cfilternsarraymaxmin

How to find a minimum and maximum values from NSArray having a custom class objects?


I have an NSArray with custom class objects having a NSNumberproperty. I am trying to fetch a minimum & maximum values from the array. So this is my code:

MyClass *minObj = [filteredArray valueForKeyPath:@"@min.self.height"];
MyClass *maxObj = [filteredArray valueForKeyPath:@"@max.self.height"];

This works and I could get a min and max values but is of NSNumber type. So minObj and maxObj will be of a number and not of MyClass type.

Is there a good way to find out the same and get the MyClass instead of NSNumber?

P.S. There can be more than one same values which can be minimum or maximum.


Solution

  • Just write code to do it. For example (typed directly into answer, expect minor typos):

    MyObj *minObj = filteredArray[0];
    for(MyObj *candidate in filteredArray)
       if([candidate.height compare:minObj.height] == NSOrderedDescending)
          minObj = candidate;
    

    You can of course find both min and max using a single pass over your array.

    HTH