|
|
|||||
|
|
|||||
|
|
Comparing NSStrings numerically Sometimes it is desirable to compare strings with numbers as part of the string. For example, a list of filenames might be:
The basic compare message for NSString, compare:, only treats the numbers as a string of characters rather than as numbers. This causes the above list to be sorted as:
Categories provide a way to add new methods to existing classes even if you do not have the source code to the original class. I created a category on NSString called numericalCompare: (originally I called it smartCompare:). It will sort our list of filenames as we expect:
My code is a direct translation of the algorithm I devised to perform the comparison and makes extensive use of NSScanner. However, it is somewhat inefficient as it stands. Fortunately, Norbert Heger provided a much more efficient routine to perform the same action. Here is the source code for numericalCompare: NumericalCompare.sit.hqx. NumericalCompare.h is the header file declaring the category. NumericalCompare.m is the definition of numericalCompare:. NorbertCompare.m is Norbert Heger's version of numericalCompare:. |