iphone - 如何使用比较:options对NSArray进行排序

标签 iphone sorting compare nsarray

我有一个 NSArray,其中包含数字作为 NSString 对象。 IE。

[array addObject:[NSString stringWithFormat:@"%d", 100]];

如何对数组进行数字排序?我可以使用 compare:options 并将 NSNumericSearch 指定为 NSStringCompareOptions 吗?请给我一个示例/示例代码。

最佳答案

您可以使用 sortedArrayUsingFunction:context: 给出的示例代码方法也应该适用于 NSStrings,因为它们也有 intValue 方法。

// Place this functions somewhere above @implementation
static 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;
}

// And used like this
NSArray *sortedArray; 
sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];

关于iphone - 如何使用比较:options对NSArray进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2031990/

相关文章:

iphone - 截屏

iphone - 如何从第二层向下建立 UINavigationController(不是从 Delegate/RootController 层)

iphone - 使用 cocos2d 应用程序降低功耗的可能性

java - 为什么我的程序在打印 letterList 数组时会跳过数字?它只打印出 A-Z 和 a-z

performance - 蛮力旅行商: Why is Haskell so much slower than C?

.net - 比较值类型 N 的对象

java - 使用一个参数在java中创建compareTo方法

iphone - CoreData prepareForDeletion 被调用无限次

sorting - 如何在lua中对多个值的表进行排序?

r - 检查变量在 R 中是否按递增顺序排列