101. NSSortDescriptor排序
来源:互联网 发布:linux oracle 日志 编辑:程序博客网 时间:2024/06/04 00:08
简介
NSSortDescriptor 可以用于对数组的排序, 可对普通数组进行简单排序, 也可以按照指定的对象的属性(或者字典的 key 值)对对象数组(或字典数组)进行排序。排序的方法分为正序和倒序两种.
方法
排列数组分为对 NSSet, NSArray, NSMutableArray,NSOrderedSet,NSMutableOrderedSet的排序, 这里只讲对数组的排序:
不可变数组方法:
-(NSArray )sortedArrayUsingDescriptors:(NSArray
简单数组排序
这里的简单数组是指数组元素为简单对象的数组, 如下面的存储着字符串对象, 或者NSNumber 等的数组.
简单数组排序 descriptionKey 可以为 nil 就能够将顺序排列好.
NSMutableArray *numArr = [[NSMutableArray alloc] init]; [numArr addObject:@"2"]; [numArr addObject:@"1"]; [numArr addObject:@"3"]; NSSortDescriptor *sd_num = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO]; NSArray *arr1 = [numArr sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd_num, nil]]; for (NSString *str in arr1) { NSLog(@"%@", str); } NSMutableArray *letterArr = [[NSMutableArray alloc] init]; [letterArr addObject:@"b"]; [letterArr addObject:@"c"]; [letterArr addObject:@"a"]; NSSortDescriptor *sd_letter = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES]; NSArray *arr2 = [letterArr sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd_letter, nil]]; for (NSString *str in arr2) { NSLog(@"%@", str); }
打印结果:
字典数组排序
如果是Employee对象或者字典数组, 就需要按照key 值来排序.
NSMutableArray *nameArr = [[NSMutableArray alloc] init]; NSMutableDictionary *person1 = [[NSMutableDictionary alloc] init]; [person1 setObject:@"zhangsan" forKey:@"name"]; NSMutableDictionary *person2 = [[NSMutableDictionary alloc] init]; [person2 setObject:@"lisi" forKey:@"name"]; NSMutableDictionary *person3 = [[NSMutableDictionary alloc] init]; [person3 setObject:@"wangwu" forKey:@"name"]; [nameArr addObject:person1]; [nameArr addObject:person2]; [nameArr addObject:person3]; NSSortDescriptor *sd_name = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]; NSArray *arr3 = [nameArr sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd_name, nil]]; for (NSMutableDictionary *md in arr3) { NSLog(@"%@", [md objectForKey:@"name"]); }
打印结果:
0 0
- 101. NSSortDescriptor排序
- NSSortDescriptor排序
- NSSortDescriptor排序
- NSSortDescriptor的使用---排序
- NSSortDescriptor(数组排序)
- NSSortDescriptor(数组排序)
- NSSortDescriptor(数组排序)
- NSSortDescriptor(数组排序)
- NSSortDescriptor(数组排序)
- NSSortDescriptor(数组排序)
- NSSortDescriptor(数组排序)
- NSSortDescriptor(数组排序)
- 数组排序NSSortDescriptor
- NSSortDescriptor(数组排序)
- NSSortDescriptor(数组排序)
- NSSortDescriptor(数组排序)
- NSSortDescriptor(数组排序)
- NSSortDescriptor排序(刚刚)
- CaysnPrinter开发包接口说明文档 - CaysnPrinter示例程序Sample1 - 20160623 - For Android
- jstree的demo
- 第12课第4.1节 字符设备驱动程序之中断方式的按键驱动_Linux异常处理结构
- Lucene/Solr/ElasticSearch搜索问题案例分析
- ubuntu14.04设置基本工作环境:搭建c 开发环境,搜狗输入法,触摸板
- 101. NSSortDescriptor排序
- 更改android app默认主题
- 初学CentOS的基本命令2
- 基于labview的USB调试小助手
- Android数据库Realm的第一次
- 骰子的研究
- 计算机图形学(三)_图元的属性_4_线的属性_1_线宽
- shareSDK自定义分享界面UI
- 传智播客UI设计结束了我脑袋别在裤腰带上的生活