使用自定义比较器对字符串的NSArray进行排序

Ste*_*ann 1 objective-c nsstring nsarray ios

我在字符串中有以下数字数组.

    08,
    03,
    11,
    06,
    01,
    09,
    12,
    07,
    02,
    10
Run Code Online (Sandbox Code Playgroud)

我希望它是:

    06,
    07,
    08,
    09,
    10,
    11,
    12,
    01,
    02,
    03
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?我在考虑使用这样的自定义比较器:

NSComparisonResult compare(NSString *numberOne, NSString *numberTwo, void *context) 
Run Code Online (Sandbox Code Playgroud)

但以前从未使用它.

任何帮助?

亲切的问候

编辑

好的,所以此刻我做到了这一点.

   NSArray *unsortedKeys = [self.sectionedKalender allKeys];

    NSMutableArray *sortedKeys = [[NSMutableArray alloc]initWithArray:[unsortedKeys sortedArrayUsingSelector:@selector(localizedCompare:)]];
Run Code Online (Sandbox Code Playgroud)

这将从01 - > 12对数组进行排序.这些数字代表我在tableview中的月份.目前在Januari开始,12月停止.我现在想要的是从六月开始到三月结束.

希望这可以解决一些问题.

Joa*_*son 7

首先,编写一个简单的比较函数;

NSInteger mySort(id num1, id num2, void *context)
{
    int v1 = ([num1 intValue]+6)%12;   // (6+6)%12 is 0, so 6 sorts first.
    int v2 = ([num2 intValue]+6)%12;

    if (v1 < v2)      return NSOrderedAscending;
    else if (v1 > v2) return NSOrderedDescending;
    else              return NSOrderedSame;
}
Run Code Online (Sandbox Code Playgroud)

然后用它来调用它 sortedArrayUsingFunction:context:

NSArray *array = [[NSArray alloc] initWithObjects:
      @"08",@"03",@"11",@"06",@"01",@"09",@"12",@"07",@"02",@"10",nil];

NSArray *sortedArray = [array sortedArrayUsingFunction:mySort context:NULL];

NSLog(@"%@", sortedArray);

> [06 07 08 09 10 11 12 01 02 03]
Run Code Online (Sandbox Code Playgroud)