Sort NSArray using another NSArray as a guide

So, imagine that you have several arrays, colors, and shapes, for example:

Colors: {
Yellow,
Blue,
Red
}

Shapes: {
Square,
Circle,
Diamond
}

Now, if I want to sort the colors alphabetically, 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 in the order in which I re-ordered Colors. I do not mean that Shapes are in alphabetical order - I mean that Shapes are in alphabetical order of colors ...?

+3
source share
2 answers

The easiest way is:

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

, , . , , . .

  • , -, ShapeKey ColourKey. , , :

    NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"ColourKey" ascending:YES];
    NSArray *sortedByColours = [colours sortedArrayUsingDescriptors:[NSArray arrayWithObject:sd];
    [sd release];
    
  • colour shape. , , @"ColourKey" @"colour" ( , ).

, @Daniel Dickison.

+1

Source: https://habr.com/ru/post/1770804/


All Articles