Objective-C sorting and objective-c sorting

Source: Internet
Author: User

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.