我有两个 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/