Objective C之數組排序

來源:互聯網
上載者:User

原文地址:https://my.oschina.net/pengloo53/blog/173810

大體上,OC中常用的數組排序有以下幾種方法:sortedArrayUsingSelector:;sortedArrayUsingComparator:;sortedArrayUsingDescriptors:

1、簡單排序(sortedArrayUsingSelector:)

如果只是對字串的排序,可以利用sortedArrayUsingSelector:方法就可以了,代碼如下

//簡單排序void sortArray1(){    NSArray *array = [NSArray arrayWithObjects:@"abc",@"456",@"123",@"789",@"ef", nil];    NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(compare:)];    NSLog(@"排序後:%@",sortedArray);}

當然,除了利用字串內建的compare:方法,也可以自己寫compare:方法,進行對象的比較;如下:

首先是建立了Person類,實現方法如下(標頭檔就省了):

#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]];//注意:基礎資料型別 (Elementary Data Type)要進行資料轉換  //如果年齡一樣,就按照名字排序    if (result == NSOrderedSame) {        result = [self.name compare:person.name];    }    //升序    return result;    //降序    //return -result;}@end

主函數代碼如下:

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、利用block文法(sortedArrayUsingComparator:)

蘋果官方提供了block文法,比較方便。其中數組排序可以用sortedArrayUsingComparator:方法,代碼如下:

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、進階排序(sortedArrayUsingDescriptors:)

如果是這樣一種情況呢。Person類裡有另外一個類的變數,比如說Person類除了name,age變數,還有一輛車Car類型,Car類裡有個name屬性。對Person對象進行排序,有這樣的要求:按照Car的name排序,如果是同一輛車,也就是Car的name相同,那麼再按照年齡進行排序,如果年齡也相同,最後按照Person的name進行排序。

上面這樣就要使用第三種方法,利用排序描述器,不多說,有興趣可以看看API介紹。代碼如下:

首先寫個Car類,實作類別Car.m代碼如下:

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

然後改寫Person類,實作類別Person.m代碼如下:

#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

主函數代碼如下:

ortArray4(){        //首先來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);

結果如下:

從結果看出,先按照age排序,如果age相同,按照car排序,如果car相同,按照name排序。

(注意:上面兩種排序方法要想實現字串顯示,請重寫description方法)

簡單嘗試一下:

    NSMutableArray *array=[NSMutableArray array];    for (int i=0; i<5; i++) {        Dog *d=[[Dog alloc]init];        d.name=[NSString stringWithFormat:@"狗狗%d",i];        d.age=arc4random()%10+21;        [array addObject:d];    }    NSLog(@"%@",array);    //1傳遞的key是KVC機制, 可以加上'.'    //2ascending控制升序降序.    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"self.age" ascending:NO];    //上句代碼等價於這句  NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];    NSArray *arr1 = [array sortedArrayUsingDescriptors:@[sort]];    NSLog(@"%@",arr1);

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.