Objective-C:使用参数对数组进行排序

ffl*_*dro 2 sorting iphone 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用以下函数对数组进行排序,但我无法将我的位置传递给选择器:

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

Ano*_*mie 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;
        }
    }];
}
Run Code Online (Sandbox Code Playgroud)

当然,如果您愿意,可以在块内调用现有方法.