0

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

Jan
  • 2,462
  • 3
  • 31
  • 56

1 Answers1

0

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;
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Ok, this sounds good. If I don't get a proper Key-Value method, I'll select your answer as the correct one. Thanks! – Jan Apr 02 '14 at 20:11
  • You can actually use an NSPredicate to accomplish this by setting a limit of 1 item. (Or for that matter you can just sort the array and grab the first item that way). Not sure if it is worth the effort over this method though. – Dima Apr 02 '14 at 20:13
  • @Dima: Determining the minimum first and then searching for a matching element is probably less effective. - And sorting an array just to find the smallest element is also slower than a simple loop, compare http://stackoverflow.com/questions/15931112/finding-the-smallest-and-biggest-value-in-nsarray-of-nsnumbers/15931719#15931719. – Martin R Apr 02 '14 at 20:16
  • I agree 100% about the sorting, definitely less effective. Not sure about an NSPredicate approach though, and that thread doesn't seem to address it. – Dima Apr 02 '14 at 20:19
  • @Dima: If you are thinking of a (Core Data) *fetch request* then you are totally right: A fetch request with a fetch limit of 1 and a sort descriptor would be the best method. - But this question was about an *array* and I don't yet see how a predicate could be used here. Am I overlooking something? – Martin R Apr 02 '14 at 20:22
  • edit: I see what you mean now. I was spacing out and misread the problem. Cheers! – Dima Apr 02 '14 at 20:25
  • I edited my previous comment agreeing with you a few minutes before you posted that so perhaps you missed it. In any case thanks for the link, as I didn't know that fast enumeration is faster than `indexesOfObjectsPassingTest`. I wonder if that occurs in all cases as if it is the case there is really no point in ever using any of those methods over a simple enumeration. – Dima Apr 02 '14 at 20:33
  • @Dima: And I removed my previous comment after noticing that you had edited yours :-) – Martin R Apr 02 '14 at 20:34