-1

I have an array of strings

NSArray *myNumbers = @[@"0.0454", @"-1.3534", @"0.345",
                             @"65", @"-0.345", @"1.35"];

How can I find the greatest numeric value (65) from this array of string?

Is there any default method or workaround for this?

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
New iOS Dev
  • 1,937
  • 7
  • 33
  • 67

1 Answers1

1

Just sort it while converting to float, then get the first or last value depends on your sort

NSString *max = [myNumbers sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        float first = [(NSString*)a floatValue];
        float second = [(NSString*)b floatValue];
        if (first > second)
            return NSOrderedAscending;
        else if (first < second)
            return NSOrderedDescending;
        return NSOrderedSame;
    }][0];

or

NSString *max = [[myNumbers sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        return [(NSString *)a compare:(NSString *)b options:NSNumericSearch];
    }] lastObject];
Tj3n
  • 9,837
  • 2
  • 24
  • 35
  • 2
    That would work, but sorting is a fairly expensive operation, and overkill if all you need is the largest item. It would be faster to simply loop through the list, saving a pointer to the largest item as you go. After one pass you'd have the largest (Which is O(n) performance, versus O(n log n) at best for a sort. I believe Apple's sort routines usually use QuickSort, which has O(n log n) performance at best, and O(n^2) in the worst case.) – Duncan C Jan 16 '17 at 03:34
  • I agree with Duncan, this is way too overkill. – GeneCode Jan 16 '17 at 04:11