我正在尝试对将参数传递给选择器的数组进行排序。 例如,我有一个位置数组,我想根据它们距某个点(例如,我当前的位置)的距离对该数组进行排序。
这是我的选择器,但我不知道如何调用它。
- (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:)];
}
最佳答案
除了 sortedArrayUsingFunction:context:
(Vladimir 已经很好地解释了),如果您的目标是 iOS 4.0 及更高版本,您可以使用 sortedArrayUsingComparator:
,因为传递的位置可以从 block 内引用。它看起来像这样:
- (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;
}
}];
}
当然,如果您愿意,您可以从 block 内调用现有方法。
关于iphone - Objective-C:使用参数对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5472333/