How to sort an array of custom objects by date in Objective C

No comments on How to sort an array of custom objects by date in Objective C

Written by

in

This is an example of sorting an array of custom objects by date in Objective C in descending order. Sorting by date is not different from sorting by NSInteger.

There are two ways to do this. First is to use NSSortDescriptor:

NSSortDescriptor *sortDescriptor = \
 [[NSSortDescriptor alloc] initWithKey:@"dateTime" \
 ascending:NO];
messagesArray = [messagesArray \
sortedArrayUsingDescriptors:[NSArray \
arrayWithObject:sortDescriptor]];

The second is to use NSComparisonResult:

 NSArray *sortedArray;
 sortedArray = [array sortedArrayUsingComparator: \
^NSComparisonResult(id a, id b) {
  NSDate *first = [(MCMessage*)a dateTime];
  NSDate *second = [(MCMessage*)b dateTime];
  return [second compare:first];
 }];
 array = sortedArray;

To sort in ascending order change this line:

return [second compare:first];

return [first compare:second];

This post helped me a lot.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *