Sort an array of a custom class object by date

I have an array of objects created from a custom class. Each object has an NSDate property. What is the easiest and fastest way to arrange all of these objects based on their date properties? (in order from the last to the last time).

+4
source share
2 answers
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"thisIsTheNameOfYourDateProperty" ascending:NO]; NSArray *orderedArray = [arrayOfCustomObjects sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; 
+18
source

Try the following:

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

There is also a way to sort the modified array in place, similar to the one above.

EDIT: I know there are other ways to do this using less code, but I really prefer block counters for all kinds of things, so I find it useful to keep practicing. You can also tweak them to use more custom sorting (ints versus objects) and actually record what happens with NSLog () ...).

+8
source

All Articles