2011-03-29 40 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]; 
}