NSSortDescriptor用于比较Cocoa/iPhone中的CLLocation对象

Coo*_*coa 3 sorting iphone cocoa geolocation core-location

我有一个CLLocation对象数组,我希望能够比较它们以获得起始CLLocation对象的距离.数学是直接的,但我很好奇是否有一个方便的排序描述符去做这个?我应该避免使用NSSortDescriptor并编写自定义比较方法+冒泡排序吗?我通常比较最多20个对象,所以它不需要超级高效.

Dav*_*ong 14

您可以为CLLocation编写一个简单的compareToLocation:类别,它返回NSOrderedAscending,NSOrderedDescending或NSOrderedSame,具体取决于self和其他CLLocation对象之间的距离.然后简单地做这样的事情:

NSArray * mySortedDistances = [myDistancesArray sortedArrayUsingSelector:@selector(compareToLocation:)];
Run Code Online (Sandbox Code Playgroud)

编辑:

像这样:

//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 distanceFromLocation:referenceLocation];
  CLLocationDistance thatDistance = [other distanceFromLocation: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;
}
Run Code Online (Sandbox Code Playgroud)