iOS array sorting

Source: Internet
Author: User

In general, there are several ways to sort the arrays commonly used in OC: sortedarrayusingselector:;sortedarrayusingcomparator:;sortedarrayusingdescriptors:.    1, simple sort (sortedarrayusingselector:) If it is just a sort of string, you can take advantage of Sortedarrayusingselector: method, code as follows//simple sort void sortArray1 () {    Nsarray *array = [Nsarray arraywithobjects:@ "abc", @ "456", @ "123", @ "789", @ "EF", nil];    Nsarray *sortedarray = [Array sortedarrayusingselector: @selector (compare:)]; NSLog (@ "After sorting:%@", Sortedarray);} Of course, in addition to the use of string compare: Method, you can also write their own compare: methods, the comparison of objects, as follows: The first is the new person class, the implementation method is as follows (the header file is saved): #import "Person.h" @    Implementation person//directly implements a static method to get the person object with name and age + (person *) Personwithage: (int) The Age Withname: (NSString *) name{    Person *person = [[Person alloc] init];    Person.age = age;    Person.name = name; return person;} Custom Sorting Method-(Nscomparisonresult) Compareperson: (person *) person{//default sorted by age Nscomparisonresult result = [[NSNumber number] WithInt:person.age] Compare:[nsnumber numberwithint:self.age]];//Note: The basic data type is for data conversion//If the age is the same, sort by name if (result = = Nsor Deredsame) {ResUlt = [Self.name compare:person.name]; } return result;    @end main function code is as follows: void SortArray2 () {Person *p1 = [person personwithage:23 withname:@ "Zhangsan"];    Person *P2 = [person personwithage:21 withname:@ "Lisi"];    Person *P3 = [person personwithage:24 withname:@ "Wangwu"];    Person *P4 = [person personwithage:24 withname:@ "Liwu"];    Person *P5 = [person personwithage:20 withname:@ "Liwu"];    Nsarray *array = [Nsarray arraywithobjects:p1,p2,p3,p4,p5, Nil];    Nsarray *sortedarray = [Array sortedarrayusingselector: @selector (Compareperson:)]; NSLog (@ "After sorting:%@", Sortedarray);} 2, using block Syntax (sortedarrayusingcomparator:) Apple has provided the block syntax, more convenient. Where array ordering can be used Sortedarrayusingcomparator: method, code as follows: void SortArray3 () {Nsarray *array = [Nsarray arraywithobjects:@ "1BC" @ "    4b6 ", @" 123 ", @" 789 ", @" 3ef ", nil]; Nsarray *sortedarray = [array sortedarrayusingcomparator:^nscomparisonresult (ID obj1, id obj2) {//The code here can refer to the above compare: default method, you can also write the custom method here, sort the object nscomparisonresult result = [Obj1 compare:obJ2];    return result;    }]; NSLog (@ "After sorting:%@", Sortedarray);} 3, Advanced Sort (sortedarrayusingdescriptors:) If this is the case? There is another class variable in the person class, such as the person class in addition to the name,age variable, there is a car type, the car class has a name attribute. To sort the person objects, there are requirements: Sort by car name, if the same car, that is, car name is the same, then sorted by age, if the same age, and finally sorted by person's name. The above is going to use the third method, using the sort descriptor, not much to say, interested to see the API introduction. The code is as follows: First write a Car class, implement the class CAR.M code as follows: #import "Car.h" @implementation car+ (Car *) Initwithname: (NSString *) name{Car *car = [Car All    OC] init];    Car.name = name; return car;} @end then rewrite the person class, implementing the class PERSON.M code as follows: #import "Person.h" #import "Car.h" @implementation person+ (Person *) Personwithage: (    int) Age Withname: (NSString *) name Withcar: (Car *) car{person *person = [[Person alloc] init];    Person.age = age;    Person.name = name;    Person.car = car; return person;} This overrides the description method, which is used for the final test of the sort result display-(NSString *) description{return [NSString stringwithformat:@ "Age was%zi, name is%@, Car is%@ ", _age,_name,_car.name];}        @end main function code is as follows: void SortArray4 () {///First 3 cars, Audi, Rolls-Royce, BMW, respectivelyCar *car1 = [car initwithname:@ "Audio"];        Car *car2 = [car initwithname:@ "Rolls-Royce"];                Car *CAR3 = [car initwithname:@ "BMW"]; Another 5 person, each to send a car, respectively, CAR2, Car1, Car1, Car3, car2 man *p1 = [man personwithage:23 withname:@ "Zhangsan" withcar:c        AR2];        Person *P2 = [person personwithage:21 withname:@ "Zhangsan" withcar:car1];        Person *P3 = [person personwithage:24 withname:@ "Lisi" withcar:car1];        Person *P4 = [person personwithage:23 withname:@ "Wangwu" WITHCAR:CAR3];            Person *P5 = [person personwithage:23 withname:@ "Wangwu" withcar:car2];                Add array Nsarray *array = [Nsarray arraywithobjects:p1,p2,p3,p4,p5, Nil];        Build the sort descriptor nssortdescriptor *carnamedesc = [Nssortdescriptor sortdescriptorwithkey:@ "Car.name" Ascending:YES];        Nssortdescriptor *personnamedesc = [nssortdescriptor sortdescriptorwithkey:@ "name" Ascending:yes]; Nssortdescriptor *personagedesc = [Nssortdescriptor sortdescriptorwithkey:@ "Age" ascending:yes]; Put the sort descriptor in the array, put in the order you want to sort the order//I am here: first according to age, then the name of the car, and finally according to the name of the person nsarray *descriptorarray = [Nsarray arraywit                Hobjects:personagedesc,carnamedesc,personnamedesc, nil];        Nsarray *sortedarray = [array Sortedarrayusingdescriptors:descriptorarray]; NSLog (@ "%@", Sortedarray);} The results are as follows: from the results, sort by age, if age is the same, sort by car, if car is the same, sort by name. (Note: The above two sorting methods to implement the string display, please override the description method)



iOS array sorting

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.