Sorting Arrays
The NSArray class offers a few
ways to sort the contents of an array, one of which will remind you
instantly of JavaScript array sorting by way of a separate function. In
all cases, pairs of array elements are compared against each other, just
as they are in JavaScript. For any two-item comparison—whether the items
are of type NSString, NSNumber, or NSDate—the sorting method reports whether the
first item is lower, higher, or the same as the second item. Those states
correspond to three simple values representing the result of the
comparison of each pair of items. The sorting mechanism of NSArray compares pairs in quick succession and
uses the results to arrange the elements. The sorted version is either
returned as a new array in the sorted order (NSArray) or applied directly to the original
array (NSMutableArray).
Your choice of sorting approach depends on the nature of the array. One approach is nicely suited to an array of simple objects (strings, numbers, and dates), while another lets you dig down deeper to sort on a key within an array of dictionaries. I’ll start with the easy one.
Sorting with a Selector
In Objective-C, a selector is a reference to a method. Whenever a method argument calls for a selector, the syntax for the argument value is as follows:
@selector(methodName)Yes, that’s a compiler directive making an appearance somewhere within a message (not out at the left margin, as you’ve seen elsewhere). The expression is analogous to JavaScript referencing ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access