2011-03-29 39 views
2

我在尝试对将参数传递给选择器的数组进行排序。 例如,我有一个位置数组,我想根据他们从某个点(例如,我的当前位置)的距离对这个数组进行排序。Objective-C:使用参数对数组进行排序

这是我的选择器,但我不知道如何调用它。

- (NSComparisonResult)compareByDistance:(POI*)otherPoint withLocation:(CLLocation*)userLocation { 
    int distance = [location distanceFromLocation:userLocation]; 
    int otherDistance = [otherPoint.location distanceFromLocation:userLocation]; 

    if(distance > otherDistance){ 
     return NSOrderedAscending; 
    } else if(distance < otherDistance){ 
     return NSOrderedDescending; 
    } else { 
     return NSOrderedSame; 
    } 
} 

我尝试使用下面的函数数组排序,但我不能把我的位置选择:

- (NSArray*)getPointsByDistance:(CLLocation*)location 
{ 
    return [points sortedArrayUsingSelector:@selector(compareByDistance:withLocation:)]; 
} 

回答

9

除了sortedArrayUsingFunction:context:(已深受弗拉基米尔解释),如果你的目标的iOS 4.0及以上,你可以使用sortedArrayUsingComparator:,作为传递的位置可以从内引用该块。这将是这个样子:

- (NSArray*)getPointsByDistance:(CLLocation*)location 
{ 
    return [points sortedArrayUsingComparator:^NSComparisonResult(id a, id b) { 
     int distance = [a distanceFromLocation:location]; 
     int otherDistance = [b distanceFromLocation:location]; 

     if(distance > otherDistance){ 
      return NSOrderedAscending; 
     } else if(distance < otherDistance){ 
      return NSOrderedDescending; 
     } else { 
      return NSOrderedSame; 
     } 
    }]; 
} 

你可以,当然,从块内调用现有的方法,如果你愿意的话。

+0

在这里IMO是一个非常好的解决方案。 – Chuck 2011-03-30 03:21:53

+0

这个解决方案正是我想要做的。弗拉基米尔的解决方案可以完成工作,但是这个更漂亮了;) – ffleandro 2011-04-04 12:19:16

+0

+1。块是真棒:) – Vladimir 2011-04-04 12:21:52

3

也许这将更加方便使用sortedArrayUsingFunction:context:排序数组方法在你的情况。你甚至可以利用比较选择你已经有了:

NSComparisonResult myDistanceSort(POI* p1, POI* p2, void* context){ 
    return [p1 compareByDistance:p2 withLocation:(CLLocation*)context]; 
} 
... 
- (NSArray*)getPointsByDistance:(CLLocation*)location 
{ 
    return [points sortedArrayUsingFunction:myDistanceSort context:location]; 
}