You can write a simple compareToLocation: category for CLLocation that returns NSOrderedAscending, NSOrderedDescending, or NSOrderedSame depending on the distance between itself and another CLLocation object. Then just do the following:
NSArray * mySortedDistances = [myDistancesArray sortedArrayUsingSelector:@selector(compareToLocation:)];
Edit:
Like this:
static CLLocation * referenceLocation;
@interface CLLocation (DistanceComparison)
- (NSComparisonResult) compareToLocation:(CLLocation *)other;
@end
@implementation CLLocation (DistanceComparison)
- (NSComparisonResult) compareToLocation:(CLLocation *)other {
CLLocationDistance thisDistance = [self distanceFromLocation:referenceLocation];
CLLocationDistance thatDistance = [other distanceFromLocation:referenceLocation];
if (thisDistance < thatDistance) { return NSOrderedAscending; }
if (thisDistance > thatDistance) { return NSOrderedDescending; }
return NSOrderedSame;
}
@end
#import CLLocation+DistanceComparison.h
- (void) someMethod {
NSArray * distances = ...;
referenceLocation = myStartingCLLocation;
NSArray * mySortedDistances = [distances sortedArrayUsingSelector:@selector(compareToLocation:)];
referenceLocation = nil;
}
source
share