Objective-C sorting and objective-c sorting
In Objective-C, sorting is divided:
1. Sort objects in the Foundation framework
2. Sorting custom objects
Example: Each student has a score attribute, Which is sorted by score.
Custom object Student. h
# Import <Foundation/Foundation. h> # import "Student. h "int main (int argc, const char * argv []) {@ autoreleasepool {// 1. NSArray * arr = @ [@ 12, @ 25, @ 15, @ 7, @ 18]; NSLog (@ "Before sorting: % @", arr); // Note: You want to use the compare method to sort the elements in the array, the elements in the array must be objects in the Foundation framework, that is, they cannot be custom objects NSArray * newArr = [arr sortedArrayUsingSelector: @ selector (compare :)]; NSLog (@ "after sorting: % @ ", newArr); // 2. Sort custom objects Student * stu1 = [Student new]; stu1.score = 91; Student * stu2 = [Student new]; stu2.score = 97; Student * stu3 = [Student new]; stu3.score = 95; Student * stu4 = [Student new]; stu4.score = 87; NSArray * studentArr = @ [stu1, stu2, stu3, stu4]; NSLog (@ "Before sorting: % @", studentArr); // sort by student scores // compare not supported: method To sort custom objects // NSArray * newArr = [arr sortedArrayUsingSelector: @ selector (compare :)]; // by default, this method will sort NSArray * newStudentArr = [studentArr sortedarraywitexceptions: NSSortStable usingComparator: ^ NSComparisonResult (Student * obj1, Student * obj2) in ascending order) {// return obj1.score> obj2.score in ascending order; // descending order // return obj1.score <obj2.score ;}]; NSLog (@ "after sorting: % @", newStudentArr ); return 0;} return 0 ;}
Result: