Sorting techniques

hardjalard

Registered
I learned these back in the day in a Comp. Sci. class I took. From what I understand of Cocoa, there is an actual method that sorts the array in ascending order. What I don't understand is how to use this method (sortWithFunction or whatever other sort methods Cocoa has). Please inform me of the safest and easiest way to sort an array using Cocoa.

Thanks in advance
 
Generally when an API provides a callback for sorting it does so at the simplest level. Your callback function receives references to two objects of some kind, and it is the job of the callback to compare the two objects and return the result of the comparison. Usually you return -1 if the first object is smaller than the second, +1 if the opposite is true, and 0 if they are equal.

The Cocoa API explicitly defines constants named NSOrderedAscending, NSOrderedDescending, and NSOrderedSame for return from your callback.

Look at the documentation for NSArray, and in particular the function method sortedArrayUsingFunction:context:. If you have XCode you can just open the documentation window from the Help menu and type NSArray in the search box.

When you send the sortedArrayUsingFunction:context: message to an NSArray the object responds by giving you a sorted copy of itself. I don't think the objects referred to by the array are duplicated at all. The array is just a list of pointers, after all.
 
Many Cocoa objects such as NSString and NSValue implement the compare: method, which does the same -1/0/1 thing as slur described. You can use this with sortedArrayUsingSelector: to sort an array of such objects. You can also implement compare: on your own classes to make them sortable.
 
Back
Top