ylliX - Online Advertising Network

Sorting an Array in Objective-C

Sorting an array is pretty simple, thanks to many helper classes you can sort not only by key but also by attributes (if you have array of objects).
Consider such array:

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

To sort it alphabetically just use:

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

and you will get such result:

Apples, Oranges, Grapes

Now consider array of objects, lets say it will be class called Person with attributes like firstName and lastName, to get it sorted by f.e. lastName use:

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

Isn’t it simple? But wait, there is more to come.
In many cases you want multiple sorting, so lets say sort persons by last name, then by first name. Here we come:

NSSortDescriptor *sort1 = [[NSSortDescriptor alloc] initWithKey:@"lastName" ascending:YES];
NSSortDescriptor *sort2 = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:NO];
data = [data sortedArrayUsingDescriptors:@[sort1, sort2]];

Example result will be:

Carmack, John
Carmack, Will

Pretty cool, huh?

Leave a Reply