Summary of several cases of array sorting in Objective C

Source: Internet
Author: User

In general, there are several ways to sort the array commonly used in OC: sortedarrayusingselector:;sortedarrayusingcomparator:;sortedarrayusingdescriptors:

1. Simple sorting (sortedarrayusingselector:)

If you just sort the string, you can take advantage of the Sortedarrayusingselector: method, the code is as follows

1 //Simple Sorting2 voidsortArray1 () {3Nsarray *array = [Nsarray arraywithobjects:@"ABC",@"456",@"123",@"789",@"EF", nil];4Nsarray *sortedarray =[Array sortedarrayusingselector: @selector (compare:)];5NSLog (@"after sorting:%@", Sortedarray);6}

Of course, in addition to the use of string compare: Method, you can also write their own compare: methods, the comparison of objects;

The first is the new person class, which is implemented as follows (the header file is saved):

1 #import "Person.h"2 @implementation Person3  4 //implement static methods directly to get a person object with name and age5+ (person *) Personwithage: (int) Age Withname: (NSString *) name{6Person *person =[[Person alloc] init];7Person.age =Age ;8Person.name =name;9     returnPerson ;Ten } One   A //Custom Sorting methods --(Nscomparisonresult) Compareperson: (Person *) person{ -   //sort by age by default theNscomparisonresult result = [[NSNumber numberWithInt:person.age] Compare:[nsnumber NumberWithInt:self.age]];//Note: Basic data types are being converted to data -   //If you are of the same age, sort by name -     if(Result = =nsorderedsame) { -result =[Self.name compare:person.name]; +     } -     returnresult; + } A   at @end

The main function code is as follows:

1 voidSortArray2 () {2Person *P1 = [Person personwithage: atWithname:@"Zhangsan"];3Person *P2 = [Person personwithage: +Withname:@"Lisi"];4Person *P3 = [Person personwithage: -Withname:@"Wangwu"];5Person *P4 = [Person personwithage: -Withname:@"Liwu"];6Person *P5 = [Person personwithage: -Withname:@"Liwu"];7Nsarray *array =[Nsarray arraywithobjects:p1,p2,p3,p4,p5, nil];8Nsarray *sortedarray =[Array sortedarrayusingselector: @selector (Compareperson:)];9NSLog (@"after sorting:%@", Sortedarray);Ten}
2. Using block Syntax (sortedarrayusingcomparator:)

Apple officially provides block syntax, which is more convenient. Where array ordering can be used Sortedarrayusingcomparator: method, the code is as follows:

1 voidsortArray3 () {2Nsarray *array = [Nsarray arraywithobjects:@"1BC",@"4b6",@"123",@"789",@"3ef", nil];3Nsarray *sortedarray = [Array Sortedarrayusingcomparator:^nscomparisonresult (IDObj1,IDobj2) {4  5    //Here the code can refer to the above compare: The default sorting method, you can also write a custom method here, to sort objects6Nscomparisonresult result =[Obj1 compare:obj2];7         returnresult;8     }];9NSLog (@"after sorting:%@", Sortedarray);Ten}
3, Advanced Sort (sortedarrayusingdescriptors:)

What 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:

1 #import "Car.h"2 @implementationCar3  4+ (Car *) Initwithname: (NSString *) name{5Car *car =[Car alloc] init];6Car.name =name;7     returncar;8 }9  Ten @end

Then rewrite the person class, implementing the class PERSON.M code as follows:

1 #import "Person.h"2 #import "Car.h"3 @implementation Person4  5+ (person *) Personwithage: (int) Age Withname: (NSString *) name Withcar: (Car *) car{6Person *person =[[Person alloc] init];7Person.age =Age ;8Person.name =name;9Person.car =car;Ten     returnPerson ; One } A   - //This overrides the description method for the final test of the sort result display --(NSString *) description{ the     return[NSString stringWithFormat:@"Age was%zi, name is%@, car is%@", _age,_name,_car.name]; - } -   - @end

The main function code is as follows:

1 voidSortArray4 () {2         //first of all, 3 cars, namely Audi, Rolls-Royce, BMW3Car *car1 = [car initwithname:@"Audio"];4Car *car2 = [car initwithname:@"Rolls-Royce"];5Car *CAR3 = [car initwithname:@"BMW"];6          7         //another 5 person, each to send a car, respectively, CAR2, Car1, Car1, Car3, Car28Person *P1 = [Person personwithage: atWithname:@"Zhangsan"WITHCAR:CAR2];9Person *P2 = [Person personwithage: +Withname:@"Zhangsan"WITHCAR:CAR1];TenPerson *P3 = [Person personwithage: -Withname:@"Lisi"WITHCAR:CAR1]; OnePerson *P4 = [Person personwithage: atWithname:@"Wangwu"WITHCAR:CAR3]; APerson *P5 = [Person personwithage: atWithname:@"Wangwu"WITHCAR:CAR2]; -   -       the         //adding arrays -Nsarray *array =[Nsarray arraywithobjects:p1,p2,p3,p4,p5, nil]; -           -         //Build a Sort descriptor +Nssortdescriptor *carnamedesc = [Nssortdescriptor sortdescriptorwithkey:@"Car.name"Ascending:yes]; -Nssortdescriptor *personnamedesc = [Nssortdescriptor sortdescriptorwithkey:@"name"Ascending:yes]; +Nssortdescriptor *personagedesc = [Nssortdescriptor sortdescriptorwithkey:@" Age"Ascending:yes]; A           at         //Put the sort descriptor in the array and put it in the order that you want it to be sorted. -         //I am here: first sort by age, then the name of the car, and finally, by the name of the person -Nsarray *descriptorarray =[Nsarray Arraywithobjects:personagedesc,carnamedesc,personnamedesc, nil]; -           -Nsarray *sortedarray =[Array Sortedarrayusingdescriptors:descriptorarray]; -NSLog (@"%@", Sortedarray); in}

The results are as follows:

As seen from the results, sort by age first, if age is the same, sort by car, if car is the same, sort by name.

Summary of several cases of array sorting in Objective C

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.