如何排序数组(把对象按照各自属性值的顺序出现在列表中)
来源:互联网 发布:网络用户的未来发展 编辑:程序博客网 时间:2024/06/05 04:08
1——使用 NSSortDescriptor(分类描述符类) 类 为每个需要用于排序的属性,创建对象;
2——创建 NSArray 数组,将所有创建的 NSSortDescriptor 对象传入这个数组中;
3——使用 NSArray 类的 sortedArrayUsingDescriptor: 方法,将2中的数组作为参数,传入该方法;
4——结果会返回一个数组,这个数组中的对象已经按照指定的属性排好顺序。
2中创建的数组对象的第一个分类描述符将会首先发挥作用,然后再是第二个,以此类推。
// Goods.h#import <Foundation/Foundation.h>@interface Goods: NSObject@property (strong) NSString *name;@property (assign) int price;-(id) initWithName:(NSString *) n price:(int) p;-(void) printResult;@end// Goods.m#import "Goods"@implementation Goods@synthesize name, price;-(id) initWithName:(NSString *) n price:(int) p {if (self = [super init]) {self.name = n;self.price = p;}return self;}-(void) printResult {NSLog(@" The price of %@ is %i.", name, price);}@end// main.m#import <Foundation/Foundation.h>#import "Goods"int main (int argc, const char * argv[]){@autoreleasepool{Goods *g1 = [[Goods alloc] initWithName:@"cookies" price:5];Goods *g2 = [[Goods alloc] initWithName:@"milk" price: 3];Goods *g3 = [[Goods alloc] initWithName:@"ice cream" price: 4];// 把所有的物品对象集中到 listOfGoods 数组对象中NSArray *listOfGoods = [NSArray arrayWithObjects: g1,g2,g3,nil];NSLog(@"输出未排序的数组对象");// 输出各个物品的名字和价格[listOfGoods makeObjectsPerformSelector: @selector(printResult)];// 创建第一个 NSSortDescriptor 对象,以名字为描述符 , 升序NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending: YES];// 创建第二个 NSSortDescriptor 对象,以价格为描述符,升 序NSSortDescriptor *sd2 = [NSSortDescriptor sortDescriptorWithKey:@"price" ascending: YES];// 把所有描述符集中到 对象数组NSArray *sdArray = [NSArray arrayWithObjects: sd1, sd2, nil];// 按照先排 name , 再排 price 的先后进行排序NSArray *sortedArray = [NSArray sortDescriptorWithKey: sdArray];NSLog(@"输出已经排好序的数组对象");[sortedArray makeObjectsPerformSelector:@selector(printResult)];}return 0;}
结果:输出未排序的数组对象The price of cookies is 5The price of milk is 3The price of ice cream is 4输出已经排好序的数组对象The price of cookies is 5The price of ice cream is 4The price of milk is 3
在先由名字为描述符排序后, 各商品的名字首字母由a~z 排序以后,再以价格由低到高排序,但前提是经过第一次排序后的数组中两个或多个相连的商品的首字母相同,否则,第一次的排序结果将不会被改变。
0 0
- 如何排序数组(把对象按照各自属性值的顺序出现在列表中)
- Java中如何把一组对象按照其某一个属性值进行排序?详见补充:
- Java中如何把一组对象按照其某一个属性值进行排序?
- 数组按照对象属性排序
- 按照list中对象的属性排序
- 数组的sort方法排序按照对象的属性排序
- 针对数组中自定义的NSObject对象按照某个属性的排序
- 在TreeSet中实现存储自定义对象,并且能够按照特定的顺序排序
- JAVA如何对ArrayList中对象按照该对象某属性排序(实例)
- Python 列表中存储类对象时按照指定属性进行排序——用于正排表的排序
- Object.keys()js 把对象按照属性名的字母顺序进行排列
- Object.keys()js 把对象按照属性名的字母顺序进行排列
- Java中对象按照属性排序
- 【Java中对象按照属性排序】
- list中对象按照属性排序
- 将对象数组按照每一组对象的key值大小进行字典顺序(ASCII值大小)升序排序
- 按照对象的某一属性进行排序
- ArrayList里的对象按照属性排序
- spring security的tag标签
- abstract class和interface区别与作用
- Android布局之weight属性解析
- window 2003 server 安装(1)
- 预告 ARC 重写:iOS 实现的 json 数据源的 O-R Mapping
- 如何排序数组(把对象按照各自属性值的顺序出现在列表中)
- linux 建立 tftp 要点
- 每天学一点(文件上传获取文件信息)
- php连接oracle9i,php无法加载php_oci8.dell解决办法
- Nginx使用webbench进行压力测试
- Android利用Fiddler进行网络数据抓包
- [Leetcode] Longest Substring Without Repeating Characters (Java)
- js中split函数的使用方法说明
- 排序算法(一):基本概念