NSSortDescriptor objects are sorted by arrays and js objects are sorted by arrays.
// Create an array
NSArray * array = @ [@ "zhangsan", @ "lisi", @ "zhonger", @ "zhubada", @ "honghunag"];
// Create a sorting condition, that is, an NSSortDescriptor object
// The first parameter indicates the attributes of the objects in the array (such as the attributes, names, and ages)
// The second parameter specifies whether the sorting method is ascending or descending.
// The meaning of ascending sorting. The default value is YES.
NSSortDescriptor * des = [[NSSortDescriptor alloc] initWithKey: @ "self" ascending: YES];
NSArray * newArray = [array sortedArrayUsingDescriptors: @ [des];
NSLog (@ "% @", newArray );
The first and second sorting conditions can be implemented.
Create a Person class
Person * p1 = [[Person alloc] initWithName: @ "zhonger" age: @ "19"];
Person * p2 = [[Person alloc] initWithName: @ "zhubada" age: @ "11"];
Person * p3 = [[Person alloc] initWithName: @ "zhubada" age: @ "1"];
Person * p4 = [[Person alloc] initWithName: @ "zhubada" age: @ "33"];
Person * p5 = [[Person alloc] initWithName: @ "hehehe" age: @ "38"];
NSArray * person = @ [p1, p2, p3, p4, p5];
NSSortDescriptor * des1 = [[NSSortDescriptor alloc] initWithKey: @ "name" ascending: YES];
NSSortDescriptor * des2 = [[NSSortDescriptor alloc] initWithKey: @ "age" ascending: NO];
NSArray * newArray1 = [person sortedArrayUsingDescriptors: @ [des1, des2];
NSLog (@ "% @", newArray1 );
/*
There are three steps to use NSSortDesriptor to sort arrays.
1. Create an array for sorting
2. Create a sorting condition. during initialization, specify the attributes of objects in the array for sorting, in ascending or descending order.
3. Sort the array according to the sorting conditions to get a sorted array (if it is a variable array, it will not generate a new array or itself)
*/
The method used by sortedArrayUsingSelecor: does not need to create NSSortDescriptor.
NSArray * strArray = @ [@ "zhonger", @ "zhubada", @ "qiuxiang", @ "tangbohu", @ "honghuang"];
NSArray * nesStr = [strArray sortedArrayUsingSelector: @ selector (compare :)]; // SEL can only be specified with @ selector (method name). If the array is sorted using this array, this method must return NSComparisionResult
NSLog (@ "newStr is % @", nesStr );
NSArray * personNewArray = [person sortedArrayUsingSelector: @ selector (compareByName :)];
NSLog (@ "-- % @", personNewArray );