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

标签 iphone objective-c sorting

我正在尝试对将参数传递给选择器的数组进行排序。 例如,我有一个位置数组,我想根据它们距某个点(例如,我当前的位置)的距离对该数组进行排序。

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

- (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/

相关文章:

iphone - 如何在 html 代码中插入图像?

objective-c - 转换日期格式 yyyy-MM-dd'T'HH :mm:ss. SSS

iphone - xml 解析器中奇怪的 iPhone 内存泄漏

ios - 使用户仅在完成操作 IOS Swift 3 后才访问 View

iphone - 为什么 NSDecimalNumber 10^-65 的平方结果是 10^126 而不是导致下溢异常?

iphone - 初始化 iPhone 应用程序核心数据的最佳方法?

iphone - 如何在 collectionView 中重新加载补充 View

java - 不使用扫描仪将文本数据存储到java数组中

algorithm - 排序列表以简化二叉树的构造

c++ - 排序和写入文件日期