1

i have time array of type nsmutablearray. and i want to sort this array in ascending time order . these are objects in array

         "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

i have waste my whole day on preparing algorithm but can't succeeded

user3129278
  • 179
  • 2
  • 3
  • 7
  • you wasted time coz your `time` is not actually `NSDate`, it is just a string. and we can only solve if you tell us how you are saving the time say in 24hrs format or 12 hour format. – Anoop Vaidya Jan 17 '14 at 12:45
  • 1
    Are the times 24 hour? What can you rely on? Do you have `NSDate` objects somewhere that you could use instead? – Wain Jan 17 '14 at 12:45
  • First write a small routine that will compare two of your dates for `> == – Hot Licks Jan 17 '14 at 12:55

2 Answers2

2

You can sort array in ascending order using following code:

NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self" ascending: YES];
return [myArray sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
gudok
  • 3,869
  • 2
  • 18
  • 29
Harunmughal
  • 357
  • 1
  • 4
0

Please ues bellow code :-

  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);
Abhishek Gupta
  • 601
  • 5
  • 15