开发者

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

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

I'd l开发者_C百科ike to sort them to show up in this order: 87, 91, 98, 100, 110.

Instead they are showing up as 100, 110, 87, 91, 98.

I can't start the array with all ints instead of strings unfortunately. Anyone have any ideas on how to tell if the array contains ONLY numbers from strings, maybe using a for loop? Then I could just convert them all to ints within the array and do the sort that way. Or maybe there is an easy way I am missing?

Let me know if anyone has any ideas.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜