1.倒序
在ios开发的过程中,经常需要使数组中的数据倒叙排列!比如将返回得到的数据,从大到小重新排列顺序
NSMutableArray *temp = [NSMutableArray
arrayWithObjects:@"5",@"1",@"4",@"2",nil];
temp = (NSMutableArray *)[[temp
reverseObjectEnumerator] allObjects];
2.升序/
降序
字符串
sortedArrayUsingSelector
//通过自带的compare方法升序排列
NSMutableArray *array =
[[NSMutableArray alloc]
initWithObjects:@"5",@"1",@"4",@"2",nil];
//通过倒序的方法进行降序排列
NSEnumerator *enumerator =
[array
reverseObjectEnumerator];
array =[[NSMutableArray
alloc]initWithArray: [enumerator
allObjects]];
字典
按Key值大小对NSDictionary排序
sortedArrayUsingSelector
NSMutableArray *array = [NSMutableArray
arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj0", [NSNumber
numberWithInt:0], nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj5", [NSNumber
numberWithInt:5], nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj2", [NSNumber
numberWithInt:2], nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj3", [NSNumber
numberWithInt:3], nil],
[NSDictionary
dictionaryWithObjectsAndKeys:@"Obj1", [NSNumber numberWithInt:1],
nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj4", [NSNumber
numberWithInt:4], nil], nil];
NSArray *resultArray = [array
sortedArrayUsingSelector:@selector(compare:)];
//因为NSDictionary没有compare的排序比较方法,所以需要我们自己写一个
- (NSComparisonResult)compare: (NSDictionary
*)otherDictionary{
NSDictionary *tempDictionary = (NSDictionary
*)self;
NSNumber *number1 = [[tempDictionary allKeys]
objectAtIndex:0];
NSNumber *number2 = [[otherDictionary allKeys]
objectAtIndex:0];
NSComparisonResult result = [number1
compare:number2];
return
result == NSOrderedDescending; // 升序
// return result == NSOrderedAscending; //
降序
}
sortedArrayUsingComparator
NSMutableArray *array = [NSMutableArray
arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj0", [NSNumber
numberWithInt:0], nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj5", [NSNumber
numberWithInt:5], nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj2", [NSNumber
numberWithInt:2], nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj3", [NSNumber
numberWithInt:3], nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj1", [NSNumber
numberWithInt:1], nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj4", [NSNumber
numberWithInt:4], nil], nil];
// NSArray *resultArray = [array
sortedArrayUsingSelector:@selector(compare:)];
NSArray *resultArray = [array
sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
NSNumber *number1 = [[obj1 allKeys] objectAtIndex:0];
NSNumber *number2 = [[obj2 allKeys] objectAtIndex:0];
NSComparisonResult result = [number1 compare:number2];
return result == NSOrderedDescending; // 升序
// return result == NSOrderedAscending; //
降序
}];