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