Search code examples
objective-cexceptionsubstringnsrange

Can't catch range out of bounds exception in Objective-c


I'm getting this error message in xCode:

-[__NSCFString substringWithRange:]: Range {18446744073709551615, 1} out of bounds; string length 71. This will become an exception for apps linked after 10.10 and iOS 8. Warning shown once per app execution.

I'm trying to find where in my code this is happening.

I have about a dozen substringWithRange methods in my project. I put try catch blocks around all of them:

 @try {
        substring = [s substringWithRange:NSMakeRange(i, j - i)];
    }
    @catch (NSException* e) {
        NSLog(@"Except: %@", e);
    }

None of the catch blocks are being executed.

I tried setting my deployment target to 8.4.

Any help would be great thanks!


Solution

  • The large value 18446744073709551615 is the value of NSNotFound (2^64-1, the largest integer that can be represented in 64 bits).

    You are probably first looking for a (sub)string in another string or so, but that substring is not found. Rather than a valid index you get back NSNotFound. Presumably you didn't expect or test for this special case and passed that NSNotFound value into an NSMakeRange(), triggering the error there.

    If there are only a handful of places where you call NSMakeRange, as you indicated, then you should be able to (1) verify this hypothesis and (2) fix the bug purely by inspection of the code.