How to sort NSMutableArray of date objects
Asked Answered
C

3

5

I'm doing some small work on sorting the date strings in the NSMutableArray, i'm getting the array from the sqlite db. If you print the array it is showing like this

date strings are ( "2011-05-01", "2011-02-01", "2012-01-08", "2012-05-08", "2010-01-09 )

I want to show the dates in ascending order. Please help me out guys..... I'm newbie to objc..

Campanula answered 2/12, 2012 at 7:26 Comment(0)
B
22

First you should convert all date Strings (which is NSString) objects to NSDate objects and then sort these dateObjects.

I believe you have dateArray containing all those strings.

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" 
                                                           ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject:descriptor];
NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];

OR

NSArray *reverseOrderUsingComparator = [dateArray sortedArrayUsingComparator: 
                                       ^(id obj1, id obj2) {
                                           return [obj2 compare:obj1];
                                       }];
Buoy answered 2/12, 2012 at 7:28 Comment(3)
The date format he showed in his question will sort correctly even as strings.Bagworm
That's unnecessary, he can just arrange the strings as they are right now.Crutchfield
Nice thanks man.... I used ur second one, but it is showing the array objects in descending order...how can i do it for ascendingCampanula
B
5

If your dates are really strings in the format YYYY-mm-dd, as in your question, then this will sort them in ascending order:

[arrayOfDates sortUsingSelector:@selector(compare:)];

That will also work if your dates are actually NSDate objects.

If you want to create a sorted copy of the array:

NSArray *sortedArray = [arrayOfDates sortedArrayUsingSelector:@selector(compare:)];
Bagworm answered 2/12, 2012 at 7:28 Comment(0)
B
1

Sorting should be done, imo, by the database, in general. sqlite3 does support order by.

Benzine answered 2/12, 2012 at 8:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.