基于一个订单两个NSMutableArrays [英] Order two NSMutableArrays based on one

查看:93
本文介绍了基于一个订单两个NSMutableArrays的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 第一个数组第二个数组
45 Test45
3 Test3
1 Test1
10 Test10
20 Test20


b $ b

这是两个数组的外观。现在我该如何命令他们这么数字,所以他们最终像:

 第一个数组第二个数组
1 Test1
3 Test3
10 Test10
20 Test20
45 Test45

谢谢!

解决方案

我会把这两个数组放入字典作为键和值。然后,您可以排序第一个数组(在字典中作为键),并以相同的顺序快速访问字典的值。注意,只有第一个数组中的对象支持 NSCopying ,因为这将是 NSDictionary 的工作原理。 >

以下代码应该这样做。它实际上很短,因为 NSDictionary 提供了一些很方便的方法。

  /将这两个数组放入字典作为键和值
NSDictionary * dictionary = [NSDictionary dictionaryWithObjects:secondArray forKeys:firstArray];
//排序第一个数组
NSArray * sortedFirstArray = [[dictionary allKeys] sortedArrayUsingSelector:@selector(compare :)];
//根据排序的第一个数组排序第二个数组
NSArray * sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];


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

Thanks!

解决方案

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.

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屋!

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