I have an NSArray on NSString's, but some of the strings are only numbers. How do I sort numerically properly?

前端 未结 2 1855
你的背包
你的背包 2020-12-06 23:02

My NSArray contains 100, 110, 91, 98, and 87, all NSStrings.

I\'d like to sort them to show up in this order: 87, 91, 98, 100, 110.

Instead they are showing

2条回答
  •  长情又很酷
    2020-12-06 23:19

    You can use the NSNumericSearch option to the NSString compare function to sort strings numerically. To do this with an NSArray, you will need to write a block or function to call the compare:options: method.

    NSArray *theStrings; // Contains strings, some of which are numbers
    NSArray *theSortedStrings = [theStrings sortedArrayUsingComparator:^(id obj1, id obj2) {
        return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
    }];
    

    This will also sort numerically if there is a numer within a string, i.e. "abcd89" will come before "abcd123".

提交回复
热议问题