基于一个 NSMutableArray 对两个 NSMutableArray 进行排序
我有两个 NSMutableArray。第一个数组的内容是数字形式的,它与第二个数组的内容配对:
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
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会将这两个数组作为键和值放入字典中。然后,您可以对第一个数组(充当字典中的键)进行排序,并以相同的顺序快速访问字典的值。请注意,只有第一个数组中的对象支持 NSCopying 时,这才有效,因为这就是 NSDictionary 的工作原理。
下面的代码应该可以做到这一点。它实际上很短,因为 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 howNSDictionary
works.The following code should do it. It's actually quite short because
NSDictionary
offers some nice convenience methods.我不会保留两个并行数组,而是保留一个模型对象数组。第一个数组中的每个数字将是一个属性的值,第二个数组中的每个字符串将是另一个属性的值。然后,您可以使用 排序描述符 对其中一个或两个属性进行排序。
一般来说,在 Cocoa 和 Cocoa Touch 中,并行数组可以工作,而模型对象可以节省工作。尽可能选择后者而不是前者。
Rather than keep two parallel arrays, I'd keep a single array of model objects. Each number from the first array would be the value of one property, and each string from the second array would be the value of the other property. You could then sort on either or both properties using sort descriptors.
Generally, in Cocoa and Cocoa Touch, parallel arrays make work while model objects save work. Prefer the latter over the former wherever you can.