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

2

4 Answers 4

17
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO];
NSArray *sortedArray = [detailsArray sortedArrayUsingDescriptors:@[sortDescriptor]];
Sign up to request clarification or add additional context in comments.

1 Comment

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

NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];

Comments

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];
}];

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.