4

I have an array of objects created from a custom class. Each object has an NSDate property. What is the easiest and quickest way to order all of these objects based on their dates properties? (in order from most recent to least recent).

2 Answers 2

19
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"thisIsTheNameOfYourDateProperty" ascending:NO];
NSArray *orderedArray = [arrayOfCustomObjects sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
Sign up to request clarification or add additional context in comments.

Comments

8

Try this:

NSArray* newArray = [array sortedArrayUsingComparator: ^NSComparisonResult(MyClass *c1, MyClass *c2)
{
    NSDate *d1 = c1.date;
    NSDate *d2 = c2.date;

    return [d1 compare:d2];
}];

There is also some way to sort a mutable array in place that is similar to the above.

EDIT: I know there are other ways to do this using less code, but I've really gotten to prefer the block enumerators for all kinds of things, so I find it useful to keep in practice. You can also tweak these to use more non-standard sorting (ints versus objects) and to actually log whats happeneing using NSLog() ...).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.