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

前端 未结 2 1850
你的背包
你的背包 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:17

    There are a whole mess of options for sorting an array; that isn't really the problem.

    The sort methods always put the objects in order. The order is up to the objects, or to you.

    So what you need to do is one of the following:

    1. Get the strings to compare themselves numerically.
    2. Get the array to ask you to compare them, then compare them numerically.

    Door number one is a trick and a half. NSString and the other class clusters don't let you inherit implementations; you can make your own string class, but you'd basically need to do everything from scratch (or wrap a string within a string and forward every message except compare: to it).

    Door number two is much easier. Nearly every one of the sort methods takes either a block or a function, which you implement; either way, the block/function takes two of the objects from the array, compares them, and returns the order they're in.

    Your block/function should send a compare:options: message to one of the two strings it receives, passing the NSNumericSearch option, and return the result.

    With NSArray asking you how the strings compare and you asking the strings how they compare numerically, the array will then sort its objects in numeric order.

    0 讨论(0)
  • 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".

    0 讨论(0)
提交回复
热议问题