Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>Compare method</h2> <p>Either you implement a compare-method for your object:</p> <pre><code>- (NSComparisonResult)compare:(Person *)otherObject { return [self.birthDate compare:otherObject.birthDate]; } NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)]; </code></pre> <h2>NSSortDescriptor (better)</h2> <p>or usually even better:</p> <pre><code>NSSortDescriptor *sortDescriptor; sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate" ascending:YES]; NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]]; </code></pre> <p>You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSSortDescriptor_Class/Reference/Reference.html" rel="noreferrer">the documentation</a>.</p> <h2>Blocks (shiny!)</h2> <p>There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:</p> <pre><code>NSArray *sortedArray; sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) { NSDate *first = [(Person*)a birthDate]; NSDate *second = [(Person*)b birthDate]; return [first compare:second]; }]; </code></pre> <h1>Performance</h1> <p>The <code>-compare:</code> and block-based methods will be quite a bit faster, in general, than using <code>NSSortDescriptor</code> as the latter relies on KVC. The primary advantage of the <code>NSSortDescriptor</code> method is that it provides a way to define your sort order using data, rather than code, which makes it easy to e.g. set things up so users can sort an <code>NSTableView</code> by clicking on the header row.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload