简体   繁体   English

如何在NSArray上使用自定义排序

[英]How to use Custom ordering on NSArray

How can I perfrom a custom sorting operation on an NSArray. 如何在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}

Whats the best way to put array B in the same order as array A without having to use keys? 将数组B与数组A置于相同顺序而不必使用键的最佳方法是什么?

Here's a way 这是一种方法

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;
}];

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). 上面的代码将B的元素排序为与A相同的顺序,并且B中的元素出现在末尾,但A中的元素不在结尾(因为NSNotFound是一个很大的数字)。 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. 该算法的唯一问题是,它将排序的算法复杂度乘以O(n) ,其中n是A中的对象数。因此,对于大A来说,它的速度将非常慢。

If you have:- 如果你有:-

NSArray A = {cat, dog, mouse, pig, donkey}

and

NSMutableArray B = {dog,cat,mouse,donkey,pig}

you can use:- 您可以使用:-

[B sortArrayUsingComparator:^NSComparisonResult(NSString *obj1,   NSString *obj2) {
    NSUInteger indexOfObj1 = [A indexOfObject: obj1];
    NSUInteger indexOfObj2 = [A indexOfObject: obj2];
    if(indexOfObj1 == NSNotFound || indexOfObj2 == NSNotFound){
        return NSOrderedSame;
    }
    else if(indexOfObj1 > indexOfObj2){
        return NSOrderedDescending;
    }

    return NSOrderedAscending;
}];

Check out sortedArrayUsingComparator , always works for me! sortedArrayUsingComparator ,对我一直有效!

Example: 例:

NSArray *sortedArray = [B sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1,   NSString *obj2) {
    //Insert custom ordering code here, this will just sort alphabetically.
    return [obj1 compare:obj2];
}];

to add custom sorting the best way is to use sotring with function 添加自定义排序的最佳方法是对函数进行排序


NSArray *B=[A sortedArrayUsingFunction:sortingFunction context:nil];
//  sortingFunction

NSInteger sortingFunction( id obj1, id obj2, void *context){ if ( //your condition ){ return NSOrderedDescending; } if ( //your condition){ return NSOrderedAscending; } return NSOrderedSame; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM