Objective-c sort

Source: Internet
Author: User

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

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.