码迷,mamicode.com
首页 > 移动开发 > 详细

iOS 数组和字典排序

时间:2015-09-12 16:10:36      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:

一、数组排序

  数组排序方式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 =@{@"price":@"30",@"name":@"liu"};
 3     NSDictionary *dic2 =@{@"price":@"150",@"name":@"huang"};
 4     NSDictionary *dic3 =@{@"price":@"37",@"name":@"yoyu"};
 5     NSDictionary *dic4 =@{@"price":@"25",@"name":@"yofu"};
 6     NSDictionary *dic5 =@{@"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         }else
22         {
23             return NSOrderedDescending;
24         }
25        
26     }];
27     //循环遍历排序后的字典数组
28     for (NSDictionary *dic in arr2)
29     {
30          NSLog(@"%@",dic);
31     }

 

iOS 数组和字典排序

标签:

原文地址:http://www.cnblogs.com/qq95230/p/4803038.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!