Question

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.

Was it helpful?

Solution 2

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]];

OTHER TIPS

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

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

will give 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.

Use qsort() from stdlib.h.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top