Search code examples
objective-cioscocoansstringnstimeinterval

Ordering NSStrings that are numbers of a particular format (ex 3:23.123)?


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.


Solution

  • 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"
    )