How to Sort An Array in Objective-C

Matthew Campbell, March 25th

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

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

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:

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:

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!