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
2009-07-03 22:56:14
Can you share an example of this?
Kevin Elliott
2009-07-17 22:50:37
@Kevin - I edited the post to include an example
Dave DeLong
2009-07-18 02:22:08
+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
2009-07-04 00:16:42
A:
How did you store the CLLocations? You cannot use an NSArray, so what are you using?
anonymoose
2010-03-12 19:29:17
Yes you can use an NSArray. CLLocation objects are NSObjects. http://developer.apple.com/iphone/library/documentation/CoreLocation/Reference/CLLocation_Class/
Peter Hosey
2010-03-13 23:47:52
When I store them in an NSArray and then pull them back out, they have been converted to NSCFStrings.
anonymoose
2010-03-15 13:01:36