0

On my tableview, prior to populating it after a search, I would like to add a minimum distance and a maximum distance of the current search in text fields at the top of the tableview. I can't seem to locate a method to do determine these parameters and my searches will vary from 2 to 50 results. I don't want to do it the hackcish way of just comparing the distance to each item from the current location in a loop. Can anyone point me to a clean method for determining min/max of an element in a mutable array?

Crask422
  • 115
  • 1
  • 9

1 Answers1

0

If you need some value from every element in an array, then you're going to have to iterate over the array somehow. There's nothing wrong with a loop. Still, there are other ways than explicit loops to go through an array. Perhaps -[NSArray enumerateObjectsUsingBlock:] will make you happy:

__block CGFloat minDistance = INF;
__block CGFloat maxDistance = -INF;
[locationsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
    CGFloat dist = // calculate distance from obj to current location
    if( dist < minDistance ){
        minDistance = dist;
    }
    if( dist > maxDistance ){
        maxDistance = dist;
    }
 }];

Other options for enumerating arrays can be found in the Collections Programming Topics document, under Enumeration.

You should also have a look at the Key-Value Collection Operators: [locationsArray valueForKey:@"@max.distance"] will pull out the maximum distance held by any of the members of the array. This may seem like exactly what you're looking for, but there's two things to be aware of. First, the objects have to already have that distance property -- you can't do any calculation as part of this procedure. Second, the property has to be an object (in this case, probably an NSNumber) not a primitive like CGFloat, because valueForKey: is going to send compare: to the result of each property access.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • I was reading up on the kvc operators last night and that seemed to be the way to go, though I couldn't get a jump start on implementing it. Thank you – Crask422 Apr 25 '12 at 17:59
  • They're pretty handy in some cases. You can also make use of them inside IB, when you're using an array controller for example. Glad I could help. – jscs Apr 25 '12 at 18:01