Search code examples
iosiphoneobjective-ckey-value-coding

How to get the object with the lowest property value from an NSArray


I have an array of CLLocation objects. If I use

CLLocation *bestLocation = [locations valueForKeyPath:@"@min.horizontalAccuracy"];

I'm getting the lowest horizontalAccuracy value. But I want the OBJECT that contains the lowest value, so that I can later get it's proper coodinates. How can I do that?

I also tried with

CLLocation *bestLocation = [locations valueForKeyPath:@"@min.self.horizontalAccuracy"];

but got the same results.

Thanks


Solution

  • I don't think there is a simple Key-Value Coding method for that, but you can loop over the array and keep track of the "best" element:

    CLLocation *bestLocation = nil;
    for (CLLocation *loc in locations) {
        if (bestLocation == nil || loc.horizontalAccuracy < bestLocation.horizontalAccuracy)
            bestLocation = loc;
    }