sorting一个NSArray使用另一个NSArray作为指导

所以,想象一下你有几个数组,颜色和形状,就像这样:

Colors: { Yellow, Blue, Red } Shapes: { Square, Circle, Diamond } 

现在,如果我想按照字母顺序排列颜色,我可以这样做:

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

但是,如何将形状sorting为与重新sorting颜色相同的顺序。 我不是说按照字母顺序放置graphics – 我的意思是把形状按颜色的字母顺序排列…?

最简单的方法可能是这样的:

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

如果颜色与数组配对,也许你应该考虑只使用一个数组而不是两个。 例如,您可以通过一种方式来构造数据,即允许您使用单个索引来查询对象的形状和颜色。 至less有几种方法来实现这一点。

  1. 使用一个字典数组,每个字典包含两个键值对,即ShapeKeyColourKey 。 一旦你build立了这个结构,你可以使用:

     NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"ColourKey" ascending:YES]; NSArray *sortedByColours = [colours sortedArrayUsingDescriptors:[NSArray arrayWithObject:sd]; [sd release]; 
  2. 使用两个属性( colourshape定义一个自定义类。 如果你使用这种方法,你可以使用上面的代码,只需用@"ColourKey"replace@"ColourKey" @"colour" (或者你select调用那个属性)。

如果你坚持维护两个单独的数组,请与@Daniel Dickison的答案一致。