ios - 基于一个订购两个 NSMutableArrays

标签 ios cocoa nsmutablearray

我有两个 NSMutableArrays。第一个的内容是数字,与第二个的内容配对:

First Array    Second Array
   45              Test45
   3               Test3
   1               Test1
   10              Test10
   20              Test20

这就是两个数组的外观。现在我怎么能对它们进行如此数字化的排序,使它们最终像这样:

First Array    Second Array
   1               Test1
   3               Test3
   10              Test10
   20              Test20
   45              Test45

谢谢!

最佳答案

我会将这两个数组作为键和值放入字典中。然后您可以对第一个数组(充当字典中的键)进行排序,并以相同的顺序快速访问字典的值。请注意,这仅在第一个数组中的对象支持 NSCopying 时才有效,因为这就是 NSDictionary 的工作方式。

下面的代码应该可以做到。它实际上很短,因为 NSDictionary 提供了一些非常方便的方法。

// Put the two arrays into a dictionary as keys and values
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:secondArray forKeys:firstArray];
// Sort the first array
NSArray *sortedFirstArray = [[dictionary allKeys] sortedArrayUsingSelector:@selector(compare:)];
// Sort the second array based on the sorted first array
NSArray *sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];

关于ios - 基于一个订购两个 NSMutableArrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8688484/

相关文章:

ios - 复制 NSArray 到成员变量

ios - 如何将自定义值插入现有的 Plist 数组数据?

ios - 验证/提交错误 : Application failed codesign verification

ios - 更新 UITableView 单元格中的 UIImageView 透明度

ios - 应用字体粗细时,设备上的字体显示不一致

xcode - 框架在我的目标之一(屏幕保护程序)中不起作用

ios - Swift 绘图应用程序 - 根据 slider 更改线宽值

ios - 使用 identifierForVendor 加密文件是否合适?

cocoa - Cocos2d 仅在首次运行应用程序时在 CCLayer 中崩溃

objective-c - 使用自定义类根据其他数组对 NSArray 进行排序