我有两个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
谢谢!
答案 0 :(得分:17)
我会将两个数组作为键和值放入字典中。然后,您可以对第一个数组(作为字典中的键)进行排序,并以相同的顺序快速访问字典的值。请注意,这仅在第一个数组中的对象支持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]];
答案 1 :(得分:8)
我保留一个模型对象数组,而不是保留两个并行数组。第一个数组中的每个数字都是一个属性的值,第二个数组中的每个字符串都是另一个属性的值。然后,您可以使用sort descriptors对其中一个或两个属性进行排序。
通常,在Cocoa和Cocoa Touch中,并行数组可以在模型对象保存工作时完成工作。无论你在哪里,都要优先选择后者。