ココア/ iPhoneでCLLocationオブジェクトを比較するためのNSSortDescriptor
-
22-08-2019 - |
質問
私はCLLocationオブジェクトの配列を持っていると私は開始CLLocationオブジェクトからの距離を取得するためにそれらを比較できるようにしたいと思います。数学は単純ですが、これを行うことについて移動する便利なソート記述子がある場合、私は興味が?私はNSSortDescriptorを避け、方法+バブルソートを比較し、カスタムを書くべきですか?私は通常、最大20個のオブジェクトを比較していますので、効率的なスーパーである必要はありません。
解決
自己と他のCLLocationオブジェクト間の距離に応じてNSOrderedAscending、NSOrderedDescending、またはNSOrderedSameのいずれかを返しますCLLocationのカテゴリ:
あなたは、単純なcompareToLocationを書くことができます。そして、単にこのような何かをします:
NSArray * mySortedDistances = [myDistancesArray sortedArrayUsingSelector:@selector(compareToLocation:)];
編集ます:
このよう
//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;
}
他のヒント
Daveの答えを改善するには...
は、iOS 4のとおり、あなたはコンパレータブロックを使用し、静的変数とカテゴリを使用することを避けることができます:
NSArray *sortedLocations = [self.locations sortedArrayUsingComparator:^NSComparisonResult(CLLocation *obj1, CLLocation *obj2) {
CLLocationDistance distance1 = [targetLocation distanceFromLocation:loc1];
CLLocationDistance distance2 = [targetLocation distanceFromLocation:loc2];
if (distance1 < distance2)
{
return NSOrderedAscending;
}
else if (distance1 > distance2)
{
return NSOrderedDescending;
}
else
{
return NSOrderedSame;
}
}];
ちょうどあなたが実際に数学を自分で行う必要はありません忘れないでください、あなたはCLLocationインスタンスメソッドを使用することができ、(移動するための方法である)カテゴリ応答に追加します:
- (CLLocationDistance)getDistanceFrom:(const CLLocation *)location
2つの位置のオブジェクト間の距離を取得する。
所属していません StackOverflow