问题
It's possible to sort an array like this:
MutableArray = [NSMutableArray arrayWithObjects:@"5",@"1",@"7,@"9",@"4", nil];
to (start big ends small):
MutableArray = [NSMutableArray arrayWithObjects:@"9",@"7",@"5,@"4",@"1", nil];
Is it also possible to sort two arrays:
MutableArray = [NSMutableArray arrayWithObjects:@"5",@"1",@"7",@"9",@"4", nil];
MutableArray = [NSMutableArray arrayWithObjects:@"Andy",@"Mike",@"Bob",@"Amy",@"Alex", nil];
to (from big to small, but Andy
got 5
point, Mike
got 1
and so on):
MutableArray = [NSMutableArray arrayWithObjects:@"9",@"7",@"5",@"4",@"1", nil];
MutableArray = [NSMutableArray arrayWithObjects:@"Amy",@"Bob",@"Andy",@"Alex",@"Mike", nil];
Is it possible to order them as a couple?
Thanks in Advance :)
回答1:
Example how to sort arrayOne
ascending and sort arrayTwo
along:
NSMutableArray *arrayOne = [NSMutableArray arrayWithObjects:@"5",@"1",@"7",@"9",@"4", nil];
NSMutableArray *arrayTwo = [NSMutableArray arrayWithObjects:@"Andy",@"Mike",@"Bob",@"Amy",@"Alex", nil];
NSDictionary *temp = [NSDictionary dictionaryWithObjects:arrayTwo forKeys:arrayOne];
NSArray *sortedArrayOne = [[temp allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSArray *sortedArrayTwo = [temp objectsForKeys:sortedArrayOne notFoundMarker:[NSNull null]];
NSLog(@"%@",sortedArrayOne);
NSLog(@"%@",sortedArrayTwo);
Workflow:
Create dictionary from the arrays ->
sort dictionary ->
create arrays from dictionary.
EDIT
Use NSSortDescriptor
with ascending:NO
to sort descending, quick example:
NSDictionary *temp = [NSDictionary dictionaryWithObjects:arrayTwo forKeys:arrayOne];
NSSortDescriptor *theDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:@selector(compare:)];
NSArray *sortedArrayOne = [[temp allKeys] sortedArrayUsingDescriptors:[NSArray arrayWithObject:theDescriptor]];
NSArray *sortedArrayTwo = [temp objectsForKeys:sortedArrayOne notFoundMarker:[NSNull null]];
回答2:
Why don't you just create some new object let's say Player
with ivars name
and score
and store instances of that class in array. Then you'll be able to sort that array as you want for any point in your code like so:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] ;
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedByName = [players sortedArrayUsingDescriptors:sortDescriptors];
or by score:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"score" ascending:NO] ;
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedByName = [players sortedArrayUsingDescriptors:sortDescriptors];
来源:https://stackoverflow.com/questions/11905724/sort-nsmutablearray-and-sort-another-nsmutablearray-along