Objective-C:使用参数对数组进行排序 [英] Objective-C: Sort array using arguments

查看:85
本文介绍了Objective-C:使用参数对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to sort an array passing an argument to the selector. For instance, I have an array of locations and I want to sort this array based on the distance they have from a certain point (for instance, my current location).

这是我的选择器,但是我不知道怎么称呼它.

This is my selector, however I don't know how to call it.

- (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;
    }
}

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

I'm trying to sort the array using the following function, but I can't pass my location to the selector:

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

推荐答案

除了sortedArrayUsingFunction:context:(弗拉基米尔(Vladimir)已有很好的解释),如果您的目标是iOS 4.0及更高版本,则可以使用sortedArrayUsingComparator:,因为传递的位置可以从块中引用.看起来像这样:

Besides sortedArrayUsingFunction:context: (already well explained by Vladimir), if you're targeting iOS 4.0 and up you could use sortedArrayUsingComparator:, as the passed location can be referenced from within the block. It would look something like this:

- (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;
        }
    }];
}

当然,您可以根据需要从该块中调用现有方法.

You could, of course, call your existing method from within the block if you so desire.

这篇关于Objective-C:使用参数对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆