Thursday, May 14, 2009

Sorting An Array in Objective-C

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] init];
[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 SortigArray[3403:20b] B
2009-03-25 16:57:58.648 SortigArray[3403:20b] A
2009-03-25 16:57:58.649 SortigArray[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 = [anArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
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 SortigArray[3537:20b] A
2009-03-25 17:07:21.833 SortigArray[3537:20b] B
2009-03-25 17:07:21.834 SortigArray[3537:20b] C

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

No comments: