代码之家  ›  专栏  ›  技术社区  ›  Coocoo4Cocoa

用于比较cocoa/iphone中cllocation对象的nsSortDescriptor

  •  3
  • Coocoo4Cocoa  · 技术社区  · 16 年前

    我有一个cllocation对象数组,我希望能够比较它们,以获得与起始cllocation对象的距离。数学是直截了当的,但我很好奇是否有一个方便的排序描述符来做这个?我应该避免nsSortDescriptor并编写一个自定义的比较方法+冒泡排序吗?我通常最多比较20个物体,所以它不需要非常高效。

    3 回复  |  直到 12 年前
        1
  •  14
  •   Kevin    13 年前

    您可以为cllocation编写一个简单的compareToLocation:类别,该类别根据自身和其他cllocation对象之间的距离返回nsorderedAscending、nsorderedDescending或nsorderedName。然后简单地这样做:

    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;
    }
    
        2
  •  2
  •   Tyler    12 年前

    为了改进戴夫的回答…

    从IOS4开始,您可以使用比较器块,避免使用静态变量和类别:

    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;
        }
    }];
    
        3
  •  1
  •   Kendall Helmstetter Gelner    16 年前

    只需添加到类别响应(这是一种方法),不要忘记您实际上不需要自己做任何数学运算,您可以使用cllocation实例方法:

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

    获取两个位置对象之间的距离。