Sorting an NSArray using another NSArray as a guide

≡放荡痞女 提交于 2019-12-10 17:44:02

问题


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


回答1:


Easiest way is probably this:

 NSDictionary *dict = [NSDictionary dictionaryWithObjects:colors forKeys:shapes];
 NSArray *sortedShapes = [dict keysSortedByValueUsingSelector:@selector(localizedCompare:)];



回答2:


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.



来源:https://stackoverflow.com/questions/3991561/sorting-an-nsarray-using-another-nsarray-as-a-guide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!