3

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

2 Answers 2

9

Easiest way is probably this:

 NSDictionary *dict = [NSDictionary dictionaryWithObjects:colors forKeys:shapes];
 NSArray *sortedShapes = [dict keysSortedByValueUsingSelector:@selector(localizedCompare:)];
Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.