How to Sort An Array in Objective-C

Matthew Campbell, March 25th, 2009

Arrays are structures used to hold a list of objects. Sometimes though you may want to sort the order that the elements appear.

Doing this is actually pretty simple once you know how, essentially you will be using the NSArray sortedArrayUsingSelector method.

For example, if you create an array like so

NSMutableArray *anArray = 
    [[NSMutableArray alloc] 
[anArray addObject:@"B"];
[anArray addObject:@"A"];
[anArray addObject:@"C"];

and then write out the contents of the array to the log using a foreach loop the results will look like this:

[Session started at 2009-03-25 16:57:55 -0400.]
2009-03-25 16:57:58.647 TipOfTheWeek[3403:20b] B
2009-03-25 16:57:58.648 TipOfTheWeek[3403:20b] A
2009-03-25 16:57:58.649 TipOfTheWeek[3403:20b] C

Obviously, the contents of the array stay in the same order in which they were inserted.

What you could do is create another array, sorted, using the sortedArrayUsingSelector method of NSArray. Here is how:

NSArray *sortedArray = 

The odd (for some anyway) piece of this code is the @selector(caseInsensitiveCompare:) component of the code. This is a method passed to the function that instructions NSArray on how to sort the array.

At any rate, if you run through the array as before and print out the results to the log you will get this:

[Session started at 2009-03-25 17:07:18 -0400.]
2009-03-25 17:07:21.832 TipOfTheWeek[3537:20b] A
2009-03-25 17:07:21.833 TipOfTheWeek[3537:20b] B
2009-03-25 17:07:21.834 TipOfTheWeek[3537:20b] C

As you can see, the this array is sorted. There you have it!

Comments, questions – a better way to do this? Let me know in the comments below!