Вопрос

I have NSStrings that represent times of the format mm:ss.SSS in my app. I am trying to generate a list of "fastest times" and I'm struggling trying to figure out what data types to use to order these numbers.

What is the easiest way to order these strings from least to greatest amount of time? I'm assuming converting to a numbered data type would do the trick, but what data type should I be using? I need to preserve the mm:ss.SSS formatting.

Это было полезно?

Решение 2

You can also use (abuse ?) localizedStandardCompare: for that purpose, because that method compares numbers embedded in the string according to their numerical value:

NSArray *times = @[ @"11:22.333", @"2:44.555" ];
NSArray *sortedTimes = [times sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
NSLog(@"%@", sortedTimes);

Output:

(
    "2:44.555",
    "11:22.333"
)

Другие советы

If you have NSString objects you can convert to NSDate objects (such as these, presumably, which you could, for example, convert into ISO 8601 format using a suitable offset), then you can sort an NSArray instance of NSDate objects very easily (example) and pick from the top or bottom of the list, depending on whether you sort in descending or ascending order.

The advantage of this approach is that you are working with standard date processing functions, which can result in less code and less debugging. Reinventing the wheel may get you a faster solution, but it can also introduce bugs.

If the strings are well-formed, with leading zeros, form an NSArray and then invoke sortedArrayUsingComparator:. But if you have values like 12:34.567 and 2:34.567, this approach won't work. You'll have to convert, either to double or NSNumber, storing seconds (that is, 2:34.567 converts to 154.567).

Note that these are not NSDate objects. An NSDate marks a particular instant in time, and these appear to be simply durations.

If you use NSNumber, you can still use sortedArrayUsingComparator:. You'll have to write a subclass of NSFormatter, to convert between mm:ss.SSS and NSNumber and back again.

See the documentation for NSComparator for a blocks-based example. You'll also need the Class Reference for NSFormatter. The FormatterKit project on GitHub has some nice NSFormatter sample code.

My advice is to create your own class that represents the datatype for mm, ss and SSS. You can then write your own prettyprint and compare methods for the datatype. The compare method itself would be fairly simple to implement and you can then use that compare method to sort an array of such objects.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top