Search code examples
iosobjective-ccocoa-touchnsscanner

NSScanner not scanning long numeric string into number


I have a string "999999999999528106" and I am passing it to NSScanner but the output is not correct. I get 2147483647 as result.

I guess the big size of my string is not fitting into the NSInteger. Any clue

    NSScanner *aScanner = [NSScanner scannerWithString:iString];
    NSMutableCharacterSet *aCharset = [NSMutableCharacterSet whitespaceAndNewlineCharacterSet];
    [aCharset formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]];
    [aScanner setCharactersToBeSkipped:[aCharset copy]];


    NSInteger anIntegerResult = 0;
    [aScanner setScanLocation:0];
    if ([aScanner scanInteger:&anIntegerResult] && aScanner.isAtEnd)
        return @(anIntegerResult);

Solution

  • From the NSScanner documentation:

    Skips past excess digits in the case of overflow, so the receiver’s position is past the entire integer representation.

    So yes, it's overflowing. You can use scanLongLong: instead.