简体   繁体   中英

Sort NSMutableArray and sort another NSMutableArray along

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 :)

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]];

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM