如何通过时间比较按升序对nsmutablearray进行排序

时间:2014-01-17 12:42:43

标签: ios iphone objective-c algorithm

我有nsmutablearray类型的时间数组。我想按升序时间顺序对此数组进行排序。这些是数组中的对象

         "9:30" at index 0
         "8:30" at index 1
         "8:45" at index 2
         "6:45" at index 3
         "7:30"  at index 4

and i want to sort this time array like this order

         "6:45" at index 0
         "7:30" at index 1
         "8:30" at index 2
         "8:45" at index 3
         "9:30" at index 4

我浪费了一整天准备算法,但不能成功

2 个答案:

答案 0 :(得分:2)

您可以使用以下代码按升序对数组进行排序:

NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self" ascending: YES];
return [myArray sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];

答案 1 :(得分:0)

请使用以下代码: -

  NSMutableArray *listOfTime = [[NSMutableArray alloc]      initWithObjects:@"9:30",@"8:30",@"8:45",@"6:45",@"7:30", nil];

NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];

NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];

NSArray *sortedArray = [listOfTime sortedArrayUsingDescriptors:sorters];


NSMutableArray *sortArray = [[NSMutableArray alloc] init];

[sortArray addObjectsFromArray:sortedArray];

NSLog(@"sortArray : %@",sortArray);