How to use Custom ordering on NSArray

邮差的信 提交于 2019-12-24 10:48:07

问题


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}

Whats the best way to put array B in the same order as array A without having to use keys?


回答1:


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). 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.




回答2:


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



回答3:


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




回答4:


Check out sortedArrayUsingComparator, always works for me!

Example:

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


来源:https://stackoverflow.com/questions/11793578/how-to-use-custom-ordering-on-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!