In objective-c, sorting is divided into:
1. Sorting objects in the foundation framework
2. Sort Custom Objects
Example: Each student has a score score attribute, according to the score score the student sort
Custom Object Student.h
Student.m
Main.m
#import<Foundation/Foundation.h>#import "Student.h"intMainintargcConst Char*argv[]) {@autoreleasepool {//1. Sorting objects in the foundation frameworkNsarray *arr = @[@ A, @ -, @ the, @7, @ -]; NSLog (@"before sorting:%@", arr); //Note: To use the Compare method to sort elements in a group, the elements in the array must be objects in the foundation framework, that is, they cannot be custom objectsNsarray *newarr =[arr sortedarrayusingselector: @selector (compare:)]; NSLog (@"after sorting:%@", NEWARR); //2. Sort Custom ObjectsStudent*STU1 = [StudentNew]; Stu1.score= the; Student*STU2 = [StudentNew]; Stu2.score= the; Student*STU3 = [StudentNew]; Stu3.score= the; Student*STU4 = [StudentNew]; Stu4.score= the; Nsarray*studentarr =@[stu1, STU2, STU3, Stu4]; NSLog (@"before sorting:%@", Studentarr); //Sort by student's grades//You cannot use the Compare: method to sort custom objects//Nsarray *newarr = [arr sortedarrayusingselector: @selector (compare:)]; //the method is sorted by default in ascending orderNsarray *newstudentarr = [Studentarr sortedarraywithoptions:nssortstable usingcomparator:^nscomparisonresult ( Student *obj1, Student *obj2) { //Ascending returnObj1.score >Obj2.score; //Descending//return Obj1.score < Obj2.score; }]; NSLog (@"after Grade:%@", Newstudentarr); return 0; } return 0;}
Results:
Objective-c sort