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
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:
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.
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"
.