views:

264

answers:

3

Hi,

I've an array of objects, the size of which I cannot predict. The contents of the array are model objects with properties of type nsstring and nsnumber.

I need to sort the array according to one of the properties, an nsnumber. How would you do it in objective-c/Cocoa? Implement quicksort or some other algorithm (which one)? Any libraries that handle that for you?

Update While the response below is correct, it only works on 10.6 and I'm targeting 10.5.

A: 

Use qsort() from stdlib.h.

Dave Hinton
If the questioner is using an `NSArray`, the stdlib's `qsort()` won't help very much.
Barry Wark
+3  A: 

NSArray has several sorting methdods. Given your array, arr,

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"numberProperty" ascending:YES];
NSArray *sortedArr = [arr sortedArrayUsingSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

will give you want you an array sorted (ascending) by @"numberProperty". Obviously, you'll have to substitute the name of the NSNumber property in your model objects for @"numberProperty".

The sorting algorithm is not specified in NSArray's sorting methods.

Barry Wark
I would add that the built-in sorts are almost always more efficient than anything you can implement by hand. You shouldn't even think of writing a custom sort before you have ironclad evidence that the built-in sorts are to slow.
TechZen
+1: Sorting and Filtering NSArray objects: http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/Collections/Articles/sortingFilteringArrays.html
Jarret Hardie
Only available in 10.6, I'm developing for 10.5 at a minimum. Sorry for not mentioning on my post.
Rui Pacheco
What? None of the methods mentioned requires 10.6. Sorting has been a part of Foundation for years and years now.
Mike Abdullah
Perhaps you refer to the convenience factory method for NSSorDescriptor, whihc arrived in 10.6? Just replace it with the equivalent alloc/initWithKey:ascending:/autorelease.
Barry Wark
A: 

This is what I came up with:

NSArray *unsortedArray = [results allValues];
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] 
        initWithKey:@"ordinalPosition" 
          ascending:YES] 
        autorelease];

NSArray *sortedArray = [unsortedArray 
                       sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
Rui Pacheco