Easily Sort an NSArray

Posted by Grego on June 28, 2015

Need to sort an NSArray in a jiffy? Not to worry! There’s an app—err, method for that! Using NSMutableArray’s built-in sortUsingDescriptors method, sorting is a snap!

Here’s an example from an app I’m working on now:

  [tempChampList sortUsingDescriptors:@[
    [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]
  ]];

Things to keep in mind:

  • This is a method of NSMutableArray, that’s NS—Mutable—Array.
  • This method requires an NSArray of descriptors
  • You must construct the NSSortDescriptor objects—how else would we know how to sort?
  • Descriptors could be properties of your objects. In my case, the NSMutableArray contains a list of objects that all have a name property.

More resources