Sorting an NSArray
While developing apps for the iPhone SDK you will almost certain come across arrays of various types NSArray being the most common. Some languages have useful utility function calls such as PHP’s asort() and the iPhone SDK is no exception providing the sortedArrayUsingSelector method for the NSArray class. So today I’m going to take a quick look at sorting an NSArray using this method.
If you have created an array like so,
NSMutableArray *aArray = [[NSMutableArray alloc] init]; [anArray addObject:@"C"]; [anArray addObject:@"B"]; [anArray addObject:@"A"];
and then write out the contents of the array using,
for (NSString *s in aArray) {
NSLog(s);
}
you should get some output showing that the objects are in the array in the order they were inserted, no big surprise there.
C
B
A
To sort this array you can create another array using the sortedArrayUsingSelector method of the NSArray class.
//sortedArray will be a new object, be //careful to relase appropriately etc NSArray *sortedArray = [anArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
The main element of the above section code is the @selector(caseInsensitiveCompare:) method. This is simply an argument passed to the sortedArrayUsingSelector method call telling it with comparison type to use when sorting your NSArray.
If you now use the logging code to output the array you just created you should see something like,
A
B
C
This is not the only way to sort an array, but it is a good start. If you are using an NSMutableArray you should be able to sort in place using
– sortUsingDescriptors: – sortUsingFunction:context: – sortUsingSelector:
So that concludes my tip for sorting any NSArray or NSMutalbeArray you have. Should come in handy!














