object-c NSArray排序转载

object-c NSArray排序转载
1.升序排列
NSArray *_firstArray = [NSArray arrayWithObjects:@"ccccc",@"bbbbb",@"ddddd",@"aaaaa",nil];
NSArray *_sortedArray= [_firstArray sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"未排序:%@",_firstArray);
NSLog(@"排行后:%@",_sortedArray);
结果:
2012-03-19 23:17:06.748 IOSSortArray[1761:f803] 未排序:(
ccccc,
bbbbb,
ddddd,
aaaaa
)
2012-03-19 23:17:06.749 IOSSortArray[1761:f803] 排行后:(
aaaaa,
bbbbb,
ccccc,
ddddd
)


2.降序排列
NSMutableArray *_reSortArray= [[NSMutableArray alloc] init];
for (id _obj in [_sortedArray reverseObjectEnumerator]) {
[_reSortArray addObject:_obj];
}
NSLog(@"降序排列:%@",_reSortArray);
[_reSortArray release];
结果:
2012-03-19 23:27:20.789 IOSSortArray[2011:f803] 排行后:(
aaaaa,
bbbbb,
ccccc,
ddddd
)
2012-03-19 23:27:20.790 IOSSortArray[2011:f803] 降序排列:(
ddddd,
ccccc,
bbbbb,
aaaaa
)


3.数组里的字典排序(NSDirector排序)
NSMutableArray *_mutiArray = [[NSMutableArray alloc] init];
[_mutiArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"rainbird",@"name",@"ddabc",@"work", nil]];
[_mutiArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"ainbird",@"name",@"ccabc",@"work", nil]];
[_mutiArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"inbird",@"name",@"fdabc",@"work", nil]];
[_mutiArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"bird",@"name",@"agbc",@"work", nil]];
[_mutiArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"rd",@"name",@"abac",@"work", nil]];

NSSortDescriptor *_sorter = [[NSSortDescriptor alloc] initWithKey:@"name"
ascending:YES];
NSSortDescriptor *_sorter2 = [[NSSortDescriptor alloc] initWithKey:@"work"
ascending:YES];
NSLog(@"未排序:\n%@",_mutiArray);
NSLog(@"根据name排序:\n%@",[_mutiArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:_sorter, nil]]);
NSLog(@"根据work排序:\n%@",[_mutiArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:_sorter2, nil]]);

[_mutiArray release];
[_sorter release];
[_sorter2 release];
结果:
2012-03-19 23:34:37.489 IOSSortArray[2119:f803] 未排序:
(
{
name = rainbird;
work = ddabc;
},
{
name = ainbird;
work = ccabc;
},
{
name = inbird;
work = fdabc;
},
{
name = bird;
work = agbc;
},
{
name = rd;
work = abac;
}
)
2012-03-19 23:34:37.490 IOSSortArray[2119:f803] 根据name排序:
(
{
name = ainbird;
work = ccabc;
},
{
name = bird;
work = agbc;
},
{
name = inbird;
work = fdabc;
},
{
name = rainbird;
work = ddabc;
},
{
name = rd;
work = abac;
}
)
2012-03-19 23:34:37.491 IOSSortArray[2119:f803] 根据work排序:
(
{
name = rd;
work = abac;
},
{
name = bird;
work = agbc;
},
{
name = ainbird;
work = ccabc;
},
{
name = rainbird;
work = ddabc;
},
{
name = inbird;
work = fdabc;
}
)

*****************
sortedArrayUsingSelector:@selector(caseInsensitiveCompare:) //不区分大小排序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值