iOS - Objective-C - Sorting an Array

Stephen Zaharuk / Wednesday, October 16, 2013

Sorting an array in objective-c is actually very easy. In this post I'll walk you through how to sort your data. 

The trick to sorting an array is a method on the array itself called "sortedArrayUsingDescriptors:". The method takes an array of NSSortDescriptor objects. These descriptors allow you to describe how your data should be sorted. 

In the simplest scenarios, if you had an array of strings:

NSArray* data = @[@"Grapes", @"Apples", @"Oranges];

And you wanted to sort it, you'd simply pass in nil for the key of the descriptor, and call the method i mentioned above:

NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
data = [data sortedArrayUsingDescriptors:@[sd]];

The output would look like:

Apples, Oranges, Grapes

So that handles the simple case, but what about if you want to sort your custom objects. In this next example, lets assume you have a class called Person. And Person had a couple of properties, "firstName" and "lastName", both types are strings. 

Now, lets sort by lastName:

NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES];
data = [data sortedArrayUsingDescriptors:@[sd]];

As you can see, we simply set the key of the SortDescriptor to the property we wanted to sort by. 

The next step, is to sort by multiple fields. So lets say you wanted to sort by lastName first - Ascending, but then sort by firstName Descending.  How would we do that?

NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES];
NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:NO];
data = [data sortedArrayUsingDescriptors:@[sd, sd2]];

Notice, all we had to do was create another NSSortDescriptor, and add it to our array. The descriptors in the front of the array have the highest priority. So in this case, the entire array is sorted by lastName. Then if some objects have the same lastName, they're sorted by firstName. 

The great thing about this "keyed" approached to sorting, is that you can actually walk down property trees.  For example, lets say you have an Employee object, that derives from our Person object. And this object has a property called "manager", which is also an Employee. If you wanted to sort your employee's by Manager's lastName, you can do that:

NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"manager.lastName" ascending:YES];
data = [data sortedArrayUsingDescriptors:@[sd]];

Thats it! We just use dot notation, and the sortedArrayUsingDescriptors knows what to do. 

By Stephen Zaharuk (SteveZ)