Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an NSArray using another NSArray as a guide

So, imagine you have a couple of arrays, Colors and Shapes, like this:

Colors: {
Yellow,
Blue,
Red
}

Shapes: {
Square,
Circle,
Diamond
}

Now, if I want to sort Colors into alphabetical order I can do something like this:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES selector:@selector(localizedCompare:)]; 
NSArray *sortedColors = [colors sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];

But how would I sort the Shapes into the same order that I re-ordered Colors. I don't mean put Shapes into alphabetical order - I mean put Shapes into Colors' alphabetical order...?

like image 320
cannyboy Avatar asked Sep 10 '26 06:09

cannyboy


1 Answers

Easiest way is probably this:

 NSDictionary *dict = [NSDictionary dictionaryWithObjects:colors forKeys:shapes];
 NSArray *sortedShapes = [dict keysSortedByValueUsingSelector:@selector(localizedCompare:)];
like image 140
Daniel Dickison Avatar answered Sep 11 '26 19:09

Daniel Dickison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!