使用另一个NSArray作为指导对NSArray进行排序 [英] Sorting an NSArray using another NSArray as a guide

查看:61
本文介绍了使用另一个NSArray作为指导对NSArray进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,假设您有几个数组,颜色和形状,如下所示:

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

推荐答案

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

Easiest way is probably this:

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

这篇关于使用另一个NSArray作为指导对NSArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆