简体   繁体   中英

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM