【问题标题】:Sorting an array of doubles or CLLocationDistance values on the iPhone在 iPhone 上对双精度数组或 CLLocationDistance 值进行排序
【发布时间】:2009-09-14 17:14:04
【问题描述】:

我正在尝试按最近距离(升序)对CLLocationDistance 值列表进行排序。我首先将这些值转换为 NSString 对象,以便我可以使用以下排序:

NSArray *sortedArray;
sortedArray = [distances sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

NSString 不能按数值排序。

如何设置升序的数值列表?

【问题讨论】:

    标签: iphone objective-c cocoa-touch arrays


    【解决方案1】:

    我认为你想要的是 sortedArrayUsingFunction:context: 使用这样的东西:

    NSInteger intSort(id num1, id num2, void *context)
    {
        int v1 = [num1 intValue];
        int v2 = [num2 intValue];
        if (v1 < v2)
            return NSOrderedAscending;
        else if (v1 > v2)
            return NSOrderedDescending;
        else
            return NSOrderedSame;
    }
    
    // sort things
    NSArray *sortedArray; sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];
    

    apple docs reference

    【讨论】:

    【解决方案2】:
    【解决方案3】:

    当您将值转换为字符串时,排序将是字典而不是数字,根据您的问题,这不是您想要的。根据 Apple 文档,CLLocationDistance 被定义为类型 double。鉴于此,创建您的 NSNumber 实例并使用您的 CLLocationDistance 数据初始化您的 NSArray(请参阅 numberWithDouble),并针对这些使用 NSArray 的排序实现。

    更多关于 NSNumber 的信息是here。

    【讨论】:

      猜你喜欢
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 2012-11-06
      • 2017-08-01
      • 1970-01-01
      相关资源
      最近更新 更多