Sorting an array with NSArray

You can think of an array as a container to hold a number of the same type of variable.
I use them a lot to hold lists of data, specifically strings! One thing that you may need to do from time to time is to sort that list in alphabetical order. This can sometimes be done [...]

You can think of an array as a container to hold a number of the same type of variable.

I use them a lot to hold lists of data, specifically strings! One thing that you may need to do from time to time is to sort that list in alphabetical order. This can sometimes be done before the list is read into the array, other times it can’t. If you are in the latter category, then you need to be able to sort the array, after it’s already loaded.

If you need to sort an array, the method is to create a second array, using the contents of the first array, which are sorted ‘into’ the second array.

// load the array with names
	NSArray *familyNames = [[NSArray alloc] initWithObjects:@"Tom", @"Dick", @"Harry", @"Obama", @"John", @"Paul", @"George", @"Ringo", nil];

//Sort the array into a sorted array called 'sortedArray'
	NSArray *sortedArray=[familyNames sortedArrayUsingSelector:@selector(compare:)];

You can then run through your code, in order to populate your control (a table for instance) without having to resort it in the back end code!

Happy coding :-)

Cheers

Graham

Tagged with:
 

Leave a Reply




Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!