根据一个排序两个 NSMutableArrays [英] Order two NSMutableArrays based on one
问题描述
我有两个 NSMutableArray.第一个的内容是数字,与第二个的内容成对:
I have two NSMutableArrays. The content of the first is numerically, which is paired to the content of the second one:
First Array Second Array
45 Test45
3 Test3
1 Test1
10 Test10
20 Test20
这就是两个数组的外观.现在我怎么能按数字顺序排列它们,所以它们最终会像:
That's the look of both arrays. Now how could I order them so numerically so they end up like:
First Array Second Array
1 Test1
3 Test3
10 Test10
20 Test20
45 Test45
谢谢!
推荐答案
我会将这两个数组作为键和值放入字典中.然后您可以对第一个数组进行排序(充当字典中的键)并以相同的顺序快速访问字典的值.请注意,这仅在第一个数组中的对象支持 NSCopying
时才有效,因为这就是 NSDictionary
的工作方式.
I would put the two arrays into a dictionary as keys and values. Then you can sort the first array (acting as keys in the dictionary) and quickly access the dictionary's values in the same order. Note that this will only work if the objects in the first array support NSCopying
because that's how NSDictionary
works.
下面的代码应该可以做到.它实际上很短,因为 NSDictionary
提供了一些不错的便捷方法.
The following code should do it. It's actually quite short because NSDictionary
offers some nice convenience methods.
// 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]];
这篇关于根据一个排序两个 NSMutableArrays的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!