一、从小到大排序
//**************************************************************************
//1.注意可变数组和不可变数组 所用的方法不同(其实直接去NSArray 和NSMutableArray 各自api中找即可)
NSArray *myArray=[NSArray arrayWithObjects:@"5",@"6",@"1",@"2",@"3",@"4", nil];
NSMutableArray *myMutableArray=[NSMutableArray arrayWithObjects:@"5",@"6",@"1",@"2",@"3",@"4", nil];
NSArray *last=[myArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 intValue]>[obj2 intValue]) {
return NSOrderedDescending;
}
else if ([obj1 intValue]<[obj2 intValue])
{
return NSOrderedAscending;
}
else
return NSOrderedSame;
}];
NSLog(@"last:%@",last);
[myMutableArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 intValue]>[obj2 intValue]) {
return NSOrderedDescending;
}
else if ([obj1 intValue]<[obj2 intValue])
{
return NSOrderedAscending;
}
else
return NSOrderedSame;
}];
NSLog(@"myMutable:%@",myMutableArray);
//**************************************************************************
//**************************************************************************
//2.可按多个关键字进行排序
NSDictionary *dic1=[NSDictionary dictionaryWithObjectsAndKeys:@"2",@"id",@"11",@"age", nil];
NSDictionary *dic2=[NSDictionary dictionaryWithObjectsAndKeys:@"1",@"id",@"13",@"age", nil];
NSDictionary *dic3=[NSDictionary dictionaryWithObjectsAndKeys:@"3",@"id",@"12",@"age", nil];
NSArray *array=[NSArray arrayWithObjects:dic1,dic2,dic3, nil];
//先按id,再按age排序 (ascending:是否是变大的顺序)
NSSortDescriptor *descriptor1=[NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES];
NSSortDescriptor *descriptor2=[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
NSArray *descriptorArray=[NSArray arrayWithObjects:descriptor1,descriptor2, nil];
NSArray *lastArray=[NSArray arrayWithArray:[array sortedArrayUsingDescriptors:descriptorArray]];
NSLog(@"lastArray:%@",lastArray);
//**************************************************************************