Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Array Using NSSortDescriptor [duplicate]

I have an array of class A objects, let it be detailsArray.

Class A has date, name as properties.

Can any one suggest a good method to sort this array based on date?

How can I use NSSortDescriptor to sort this array? I know sorting array of dictionary using NSSortDescriptor...

Any help is greatly appreciated.....

like image 938
Ab'initio Avatar asked Mar 21 '13 06:03

Ab'initio


3 Answers

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
NSArray *sortedArray = [detailsArray sortedArrayUsingDescriptors:@[sortDescriptor]];
like image 176
Nick C Avatar answered Oct 08 '22 23:10

Nick C


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

NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];
like image 30
Anoop Vaidya Avatar answered Oct 09 '22 00:10

Anoop Vaidya


NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"date"
                                              ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [yourArray sortedArrayUsingDescriptors:sortDescriptors];

or you can use a block also

NSArray *sortedArray;
sortedArray = [yourArray sortedArrayUsingComparator:^NSComparisonResult(A *a, A *b) {
    NSDate *first = a.date;
    NSDate *second = b.date;
    return [first compare:second];
}];
like image 25
Inder Kumar Rathore Avatar answered Oct 09 '22 01:10

Inder Kumar Rathore