使用另一个NSArray作为指南对NSArray进行排序(Sorting an NSArray using another NSArray as a guide)
所以,想象你有几个数组,颜色和形状,就像这样:
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];但是,如何将Shapes排序为与重新排序Colors相同的顺序。 我不是说按字母顺序放置图形 - 我的意思是把形状按颜色的字母顺序排列......?
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...?
最满意答案
最简单的方法可能是这样的:
NSDictionary *dict = [NSDictionary dictionaryWithObjects:colors forKeys:shapes]; NSArray *sortedShapes = [dict keysSortedByValueUsingSelector:@selector(localizedCompare:)];Easiest way is probably this:
NSDictionary *dict = [NSDictionary dictionaryWithObjects:colors forKeys:shapes]; NSArray *sortedShapes = [dict keysSortedByValueUsingSelector:@selector(localizedCompare:)];更多推荐
发布评论