views:

68

answers:

2

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...?

+3  A: 

Easiest way is probably this:

 NSDictionary *dict = [NSDictionary dictionaryWithObjects:colors forKeys:shapes];
 NSArray *sortedShapes = [dict keysSortedByValueUsingSelector:@selector(localizedCompare:)];
Daniel Dickison
dreamlax's answer is definitely the "cleaner" and more general solution (works with any number of arrays, not just two). I think of this one as more of a quick hack.
Daniel Dickison
+1  A: 

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.

  1. 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];
    
  2. 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.

dreamlax