Sorting Array Using NSSortDescriptor [duplicate]
Asked Answered
D

4

6

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.....

Dispraise answered 21/3, 2013 at 6:26 Comment(2)
Check my answer here #13667788Dittography
I didn't see it, Sorry....Sadiesadira
Z
17
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
NSArray *sortedArray = [detailsArray sortedArrayUsingDescriptors:@[sortDescriptor]];
Zalucki answered 21/3, 2013 at 6:34 Comment(1)
Should be: sortedArrayUsingDescriptorsMittiemittimus
D
5
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject: descriptor];

NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];
Dittography answered 21/3, 2013 at 6:33 Comment(0)
B
3
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];
}];
Blue answered 21/3, 2013 at 6:31 Comment(0)
P
1

You need to give key forward by its class name, like

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"ClassA.date" ascending:YES];

and do google your queries before ask any question, see the google crawler result.

Phanotron answered 21/3, 2013 at 6:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.