2009-07-03 9 views
3

私はCLLocationオブジェクトの配列を持っています。これらのオブジェクトを比較して、開始CLLocationオブジェクトからの距離を取得したいと考えています。数学はまっすぐですが、これを行うための便利な並べ替え記述子があれば私は興味がありますか?私はNSSortDescriptorを避け、カスタム比較メソッド+バブルソートを書くべきですか?私は通常、最大20個のオブジェクトを比較しているので、効率的なスーパーである必要はありません。Cocoa/iPhoneのCLLocationオブジェクトを比較するためのNSSortDescriptor

答えて

14

自己と他の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; 
} 
+0

あなたがの例を共有することができますこの? –

+0

@ケビン - 私は例を含むように投稿を編集しました –

+1

私はこれをあなたがここに持っているのとまったく同じように実装しようとしました。 static varは常にnilなので、まったくソートしません。何か不足していますか? –

1

ジャスト(移動するための方法である)カテゴリレスポンスに追加する、忘れないでください:

このように、単にこのような何かを行いますCLLocationインスタンスメソッドを使用することができます:

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

2つの場所オブジェクト間の距離。 Daveの答えを改善する

2

...の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; 
    } 
}]; 
+0

私はそれが "obj1"、 "obj2"ではなく、 "loc1"、 "loc2"であるべきだと思います。 – Pochi

関連する問題