Reputation: 24426
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...?
Upvotes: 3
Views: 1261
Reputation: 95355
If the colours are paired with the arrays, perhaps you should consider using just one array instead of two. For example, you could structure your data in a way that allows you to query both the shape and colour of an object using a single index. There are at least a couple of ways to achieve this.
Use an array of dictionaries, each dictionary contains two key-value pairs, ShapeKey
and ColourKey
. Once you have established this structure, you can use:
NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"ColourKey" ascending:YES];
NSArray *sortedByColours = [colours sortedArrayUsingDescriptors:[NSArray arrayWithObject:sd];
[sd release];
Define a custom class with two properties, colour
and shape
. If you use this approach, you can use the code above but simply replace @"ColourKey"
with @"colour"
(or whatever you chose to call that property).
If you insist on maintaining two separate arrays, go with @Daniel Dickison's answer.
Upvotes: 1
Reputation: 21882
Easiest way is probably this:
NSDictionary *dict = [NSDictionary dictionaryWithObjects:colors forKeys:shapes];
NSArray *sortedShapes = [dict keysSortedByValueUsingSelector:@selector(localizedCompare:)];
Upvotes: 9