IOS--常用類--NSArray

來源:互聯網
上載者:User

標籤:des   io   os   ar   sp   on   cti   log   bs   

一、從小到大排序

  //**************************************************************************

    //1.注意可變數組和不可變數組 所用的方法不同(其實直接去NSArray 和NSMutableArray 各自api中找即可)

    NSArray *myArray=[NSArray arrayWithObjects:@"5",@"6",@"1",@"2",@"3",@"4", nil];

    NSMutableArray *myMutableArray=[NSMutableArray arrayWithObjects:@"5",@"6",@"1",@"2",@"3",@"4", nil];

    

    NSArray *last=[myArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        if ([obj1 intValue]>[obj2 intValue]) {

            return NSOrderedDescending;

        }

        else if ([obj1 intValue]<[obj2 intValue])

        {

            return NSOrderedAscending;

        }

        else

            return NSOrderedSame;

    }];

    NSLog(@"last:%@",last);

    

    [myMutableArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        if ([obj1 intValue]>[obj2 intValue]) {

            return NSOrderedDescending;

        }

        else if ([obj1 intValue]<[obj2 intValue])

        {

            return NSOrderedAscending;

        }

        else

            return NSOrderedSame;

    }];

    NSLog(@"myMutable:%@",myMutableArray);

    //**************************************************************************

    

    //**************************************************************************

    //2.可按多個關鍵字進行排序

    NSDictionary *dic1=[NSDictionary dictionaryWithObjectsAndKeys:@"2",@"id",@"11",@"age", nil];

    NSDictionary *dic2=[NSDictionary dictionaryWithObjectsAndKeys:@"1",@"id",@"13",@"age", nil];

    NSDictionary *dic3=[NSDictionary dictionaryWithObjectsAndKeys:@"3",@"id",@"12",@"age", nil];

    NSArray *array=[NSArray arrayWithObjects:dic1,dic2,dic3, nil];

    

    //先按id,再按age排序 (ascending:是否是變大的順序)

    NSSortDescriptor *descriptor1=[NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES];

    NSSortDescriptor *descriptor2=[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];

    NSArray *descriptorArray=[NSArray arrayWithObjects:descriptor1,descriptor2, nil];

    

    NSArray *lastArray=[NSArray arrayWithArray:[array sortedArrayUsingDescriptors:descriptorArray]];

    NSLog(@"lastArray:%@",lastArray);

    //**************************************************************************

IOS--常用類--NSArray

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.