Create an array
nsarray *array = @[@ "Zhangsan", @ "Lisi", @ "Zhonger", @ "Zhubada", @ "Honghunag"];
// Create a sort condition, i.e. a nssortdescriptor object
/// where the first parameter is an array of attributes to be sorted by ( such as self, name, age, etc. )
///The second parameter specifies whether the sort order is ascending or descending
//ascending The meaning of the sort, the default is YES ascending
nssortdescriptor *des = [[nssortdescriptor alloc] initwithkey:@ "Self" Ascending:YES];
nsarray *newarray = [array sortedarrayusingdescriptors:@[des]];
NSLog(@ "%@", NewArray);
You can implement the first sort condition and the second sort condition
Create a Person class
person *p1 = [[person alloc] initwithname:@ ' Zhonger ' age : @ "+"];
person *p2 = [[person alloc] initwithname:@ ' Zhubada ' age :@ ' "];
person *p3 = [[person alloc] initwithname:@ ' Zhubada ' age :@ "1"];
person *p4 = [[person alloc] initwithname:@ ' Zhubada ' age :@ ' "];
person *p5 = [[person alloc] initwithname:@ ' hehehe ' age : @ "" "];
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 sorting an array using Nssortdesriptor
1. create an array to sort
2. Create a sort condition in which you need to specify what properties of an object in the array to sort by, ascending or descending
3. The array is sorted according to the sorting criteria, and a sorted array is obtained (if it is a mutable array, no new array is generated, or itself)
*/
using the Sortedarrayusingselecor: method, you do not need to create Nssortdescriptor
nsarray *strarray = @[@ "Zhonger", @ "Zhubada", @ "Qiuxiang", @ "Tangbohu" , @ "Honghuang"];
nsarray *nesstr = [Strarray sortedarrayusingselector:@selector(compare:)]; //sel can only begiven by @selector (method name), and if the array is sorted using this array, this method must be a return value of Nscomparisionresult
NSLog(@ "Newstr is%@", nesstr);
nsarray *personnewarray = [Person sortedarrayusingselector:@selector(comparebyname:)];
NSLog(@ "--%@", Personnewarray);
Nssortdescriptor objects for array sorting