views:

1554

answers:

3

I have an array of CLLocation objects and I'd like to be able to compare them to get distance from a starting CLLocation object. The math is straight forward but I'm curious if there is a convenience sort descriptor to go about doing this? Should I avoid NSSortDescriptor and write a custom compare method + bubble sort? I'm usually comparing at most 20 objects, so it doesn't need to be super efficient.

+8  A: 

You can write a simple compareToLocation: category for CLLocation that returns either NSOrderedAscending, NSOrderedDescending, or NSOrderedSame depending on the distances between self and the other CLLocation object. Then simply do something like this:

NSArray * mySortedDistances = [myDistancesArray sortedArrayUsingSelector:@selector(compareToLocation:)];

Edit:

Like this:

//CLLocation+DistanceComparison.h
static CLLocation * referenceLocation;
@interface CLLocation (DistanceComparison)
- (NSComparisonResult) compareToLocation:(CLLocation *)other;
@end

//CLLocation+DistanceComparison.m
@implementation CLLocation (DistanceComparison)
- (NSComparisonResult) compareToLocation:(CLLocation *)other {
  CLLocationDistance thisDistance = [self getDistanceFrom:referenceLocation];
  CLLocationDistance thatDistance = [other getDistanceFrom:referenceLocation];
  if (thisDistance < thatDistance) { return NSOrderedAscending; }
  if (thisDistance > thatDistance) { return NSOrderedDescending; }
  return NSOrderedSame;
}
@end


//somewhere else in your code
#import CLLocation+DistanceComparison.h
- (void) someMethod {
  //this is your array of CLLocations
  NSArray * distances = ...;
  referenceLocation = myStartingCLLocation;
  NSArray * mySortedDistances = [distances sortedArrayUsingSelector:@selector(compareToLocation:)];
  referenceLocation = nil;
}
Dave DeLong
Can you share an example of this?
Kevin Elliott
@Kevin - I edited the post to include an example
Dave DeLong
+2  A: 

Just to add to the category response (which is the way to go), don't forget you don't actually need to do any math yourself, you can use the CLLocation instance method:

- (CLLocationDistance)getDistanceFrom:(const CLLocation *)location

To get the distance between two location objects.

Kendall Helmstetter Gelner
A: 

How did you store the CLLocations? You cannot use an NSArray, so what are you using?

anonymoose
Yes you can use an NSArray. CLLocation objects are NSObjects. http://developer.apple.com/iphone/library/documentation/CoreLocation/Reference/CLLocation_Class/
Peter Hosey
When I store them in an NSArray and then pull them back out, they have been converted to NSCFStrings.
anonymoose
Nevermind, I am an idiot. I fatfingered something.
anonymoose