iOS 數組和字典排序

來源:互聯網
上載者:User

標籤:

一、數組排序

  數組排序方式1:

 1 //初始化可變數組 2         NSMutableArray *arr1=[NSMutableArray arrayWithObjects:@"giu",@"min",@"Deng",@"liumin", nil]; 3         //字串排序 4         //建立排序描述符對象NSSortDescriptor,key為空白,ascending:升序 5         NSSortDescriptor *decri =[NSSortDescriptor sortDescriptorWithKey:nil ascending:YES]; 6         //定義一個數組,用來盛放排序條件 7         NSArray *des =[NSArray arrayWithObject:decri]; 8         //開始排序 9         [arr1 sortUsingDescriptors:des];10         //列印排序內容11         for (int i=0; i<arr1.count; i++)12         {13             NSLog(@"arr=%@",[arr1 objectAtIndex:i]);14         }

 數組排序方式2:

1    NSMutableArray *arr2=[NSMutableArray arrayWithObjects:@"c", @"A",@"z",@"D",nil];2         3         //區分大小寫排序 內建compar方法  選擇排序4         [arr2 sortUsingSelector:@selector(compare:)];5         for (int i=0; i<arr2.count; i++)6         {7             NSLog(@"arr2=%@",[arr2 objectAtIndex:i]);8         }

二、字典的排序 

 1 //建立5個排序對象 2     NSDictionary *dic1 [email protected]{@"price":@"30",@"name":@"liu"}; 3     NSDictionary *dic2 [email protected]{@"price":@"150",@"name":@"huang"}; 4     NSDictionary *dic3 [email protected]{@"price":@"37",@"name":@"yoyu"}; 5     NSDictionary *dic4 [email protected]{@"price":@"25",@"name":@"yofu"}; 6     NSDictionary *dic5 [email protected]{@"price":@"172",@"name":@"yosu"}; 7     //將這些對象放進數組 8     NSArray *arr =[NSArray arrayWithObjects:dic1,dic2,dic3,dic4, dic5,nil]; 9     //調用數組排序方法10     NSArray *arr2 = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)11     {12         //取出對象裡的一個值作比較,根據大小返回結果13         NSString  *c = [obj1 valueForKey:@"price"];14         NSString  *d = [obj2 valueForKey:@"price"];15         int a =[c intValue]; //轉成整形int比較16         int b =[d intValue];17         //按照降序排列,如果升序就返回結果對換18         if (a > b)19         {20             return NSOrderedAscending;21         }else22         {23             return NSOrderedDescending;24         }25        26     }];27     //迴圈遍曆排序後的字典數組28     for (NSDictionary *dic in arr2)29     {30          NSLog(@"%@",dic);31     }

 

iOS 數組和字典排序

聯繫我們

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