使用另一个NSArray作为指南对NSArray进行排序(Sorting an NSArray using another NSArray as a guide)

编程入门 行业动态 更新时间:2024-10-24 00:29:54
使用另一个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:)];

更多推荐

本文发布于:2023-07-24 20:05:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250542.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指南   NSArray   guide   Sorting

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!