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 5
The price of milk is 3
The price of ice cream is 4
输出已经排好序的数组对象
The price of cookies is 5
The price of ice cream is 4
The price of milk is 3
在先由名字为描述符排序后, 各商品的名字首字母由a~z 排序以后,再以价格由低到高排序,但前提是经过第一次排序后的数组中两个或多个相连的商品的首字母相同,否则,第一次的排序结果将不会被改变。