如何在 NSArray 上使用自定义排序 [英] How to use Custom ordering on NSArray
问题描述
如何在 NSArray 上执行自定义排序操作.我有一组字符串,这是我想要的顺序.
How can I perfrom a custom sorting operation on an NSArray. I have one array of strings which is my ordering that I want.
NSArray A = {cat, dog, mouse, pig, donkey}
而且我有一个字符串数组,但没有按照我想要的方式排序.
And I have one array of strings which is not ordered the way I want.
NSArray B = {dog,cat,mouse,donkey,pig}
在不使用键的情况下将数组 B 与数组 A 的顺序相同的最佳方法是什么?
Whats the best way to put array B in the same order as array A without having to use keys?
推荐答案
这里有一个方法
NSArray *sortedArray = [B sortedArrayUsingComparator: ^(id obj1, id obj2){
NSUInteger index1 = [A indexOfObject: obj1];
NSUInteger index2 = [A indexOfObject: obj2];
NSComparisonResult ret = NSOrderedSame;
if (index1 < index2)
{
ret = NSOrderedAscending;
}
else if (index1 > index2)
{
ret = NSOrderedDescending;
}
return ret;
}];
以上将按照与 A 相同的顺序对 B 中的元素进行排序,其中 B 中但不在 A 中的元素出现在最后(因为 NSNotFound
是一个非常大的数字).该算法的唯一问题是它将排序的算法复杂度乘以 O(n)
,其中 n
是 A 中对象的数量.所以对于大 A,它会很慢.
The above will sort the elements of B into the same order as A with elements that are in B but not in A appearing at the end (since NSNotFound
is a very big number). The only problem with the algorithm is that it multiplies the algorithmic complexity of the sort by O(n)
where n
is the number of objects in A. So for large A it will be pretty slow.
这篇关于如何在 NSArray 上使用自定义排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!