Summary of several cases of array sorting in Objective C

Source: Internet
Author: User
Tags array sort

Summary Summary 3 ways to sort arrays in OC: sortedarrayusingselector:;sortedarrayusingcomparator:;sortedarrayusingdescriptors:

Array sort objective-c

Catalogue [-]

    • 1. Simple sorting (sortedarrayusingselector:)
    • 2. Using block Syntax (sortedarrayusingcomparator:)
    • 3, Advanced Sort (sortedarrayusingdescriptors:)

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

?
123456 //简单排序void sortArray1(){    NSArray *array = [NSArray arrayWithObjects:@"abc",@"456",@"123",@"789",@"ef", nil];    NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(compare:)];    NSLog(@"排序后:%@",sortedArray);}
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):

?
1234567891011121314151617181920212223 #import "Person.h"@implementation Person//直接实现静态方法,获取带有name和age的Person对象+(Person *)personWithAge:(int) age withName:(NSString *)name{    Person *person = [[Person alloc] init];    person.age = age;    person.name = name;    return person;}//自定义排序方法-(NSComparisonResult)comparePerson:(Person *)person{  //默认按年龄排序    NSComparisonResult result = [[NSNumber numberWithInt:person.age] compare:[NSNumber numberWithInt:self.age]];//注意:基本数据类型要进行数据转换  //如果年龄一样,就按照名字排序    if (result == NSOrderedSame) {        result = [self.name compare:person.name];    }    return result;}@end
The main function code is as follows:?
12345678910 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(@"排序后:%@",sortedArray);}
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:

?
12345678910 void sortArray3(){    NSArray *array = [NSArray arrayWithObjects:@"1bc",@"4b6",@"123",@"789",@"3ef", nil];    NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {   //这里的代码可以参照上面compare:默认的排序方法,也可以把自定义的方法写在这里,给对象排序        NSComparisonResult result = [obj1 compare:obj2];        return result;    }];    NSLog(@"排序后:%@",sortedArray);}

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:

?
12345678910 #import "Car.h"@implementation Car+(Car *)initWithName:(NSString *)name{    Car *car = [Car alloc] init];    car.name = name;    return car;}@end

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

?
123456789101112131415161718 #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;}//这里重写description方法,用于最后测试排序结果显示-(NSString *)description{    return [NSString stringWithFormat:@"age is %zi , name is %@, car is %@",_age,_name,_car.name];}@end
The main function code is as follows:?
1234567891011121314151617181920212223242526272829 void sortArray4(){        //首先来3辆车,分别是奥迪、劳斯莱斯、宝马        Car *car1 = [Car initWithName:@"Audio"];        Car *car2 = [Car initWithName:@"Rolls-Royce"];        Car *car3 = [Car initWithName:@"BMW"];                //再来5个Person,每人送辆车,分别为car2、car1、car1、car3、car2        Person *p1 = [Person personWithAge:23 withName:@"zhangsan" withCar:car2];        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];             //加入数组        NSArray *array = [NSArray arrayWithObjects:p1,p2,p3,p4,p5, nil];                //构建排序描述器        NSSortDescriptor *carNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"car.name" ascending:YES];        NSSortDescriptor *personNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];        NSSortDescriptor *personAgeDesc = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];                //把排序描述器放进数组里,放入的顺序就是你想要排序的顺序        //我这里是:首先按照年龄排序,然后是车的名字,最后是按照人的名字        NSArray *descriptorArray = [NSArray arrayWithObjects:personAgeDesc,carNameDesc,personNameDesc, nil];                NSArray *sortedArray = [array sortedArrayUsingDescriptors: descriptorArray];        NSLog(@"%@",sortedArray);}
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.