如何排序数组(把对象按照各自属性值的顺序出现在列表中)



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 排序以后,再以价格由低到高排序,但前提是经过第一次排序后的数组中两个或多个相连的商品的首字母相同,否则,第一次的排序结果将不会被改变。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值