標籤:
一、數組排序
數組排序方式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 數組和字典排序