Search code examples
iosobjective-cnsmutablearraynssortdescriptor

Sort an NSMutableArray within an NSMutableArray by date property


I have a NSMutableArray that has a inner NSMutableArray that I would like to sort (sort the outer items) by a date property within the inner NSMutableArray.

The array looks like this
[
  {
     messages : [
     { 
     date
     },
     ..... etc
     ]
  },
..... etc
]

The code below is my attempt that throws an exception

NSSortDescriptor *sdSortDate = [NSSortDescriptor sortDescriptorWithKey:@"[email protected]" ascending:YES];
events = [NSMutableArray arrayWithArray:[events sortedArrayUsingDescriptors:@[sdSortDate]]];

example

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '[<__NSArrayM 0x604000654670> valueForKeyPath:]: this class does not implement the lastObject operation.'

Any ideas on how I can do this?


Solution

  • You should use messages.date.@lastObject instead of [email protected]. Try the code below

    NSSortDescriptor *sdSortDate = [NSSortDescriptor sortDescriptorWithKey:@"messages.date.@lastObject" ascending:YES];
    events = [NSMutableArray arrayWithArray:[events sortedArrayUsingDescriptors:@[sdSortDate]]];