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
  • 199
  • 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 `> == <`, taking into account the format (eg, 12:00:00 needs to sort after 9:00:00, even though the latter is "lexically" later). Then you can use one of the NSArray/NSMutableArray sort routines to do your sort, using that routine. – 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
  • 4,029
  • 2
  • 20
  • 30
Harunmughal
  • 367
  • 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
  • 16
  • 1
    Since you're comparining strings, wouldn't "10:30" sort before "9:30"? (not what you want). You need a comparer with NSDates or a consistent format (09:30, 10:30) and you need to consider 24 hours (2 pm is not before 10 am) – bryanmac Jan 17 '14 at 13:30
  • This is marked as the answer but won't work after 9:59 am. – bryanmac Jan 17 '14 at 13:32
  • @bryanmac please wait i am doing some code for this issue – Abhishek Gupta Jan 17 '14 at 13:37