Search code examples
iosobjective-cnsrangensrangeexception

substringWithRange out of bounds--what am I missing?


I'm trying to extract some strings from some code, and I'm coming up against an NSRangeException I don't understand. Here's my code:

NSString *start = @"<strong><span class='target'>";
NSString *end = @"</span></strong> ";

NSRange startRange = [stringToScan rangeOfString:start];
NSRange endRange = [stringToScan rangeOfString:end];
NSRange targetRange;
targetRange.length = endRange.location - startRange.location - startRange.length;
targetRange.location = startRange.location + startRange.length;
NSString *adlerNumber = [stringToScan substringWithRange:targetRange];
NSLog(@"%@",adlerNumber);

NSString *startHeadword = @"Translated headword: </strong>";
NSString *endHeadword = @"<strong class=";

NSRange startRangeHeadword = [stringToScan rangeOfString:startHeadword]; //logs as e.g. location 773, length 29
NSRange endRangeHeadword = [stringToScan rangeOfString:endHeadword]; //logs as e.g. location 809
NSRange targetRangeHeadword;
targetRangeHeadword.length = endRangeHeadword.location - startRangeHeadword.location - startRangeHeadword.length; //logs as e.g. 27
targetRangeHeadword.location = startRangeHeadword.location + startRangeHeadword.length; // logs as e.g. 2496
NSString *translatedHeadword = [stringToScan substringWithRange:targetRangeHeadword];

adlerNumber is created and logs without error. But then trying to create translatedHeadword (last line of code above) gives me this error:

Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString substringWithRange:]: Range {2634, 2147481013} out of bounds; string length 9309'

If targetRangeHeadword.length logs as 27 and targetRangeHeadword.location logs as 2496, how can I be getting the numbers the NSRangeException is giving me? And how do I fix this?

Thanks in advance for your help, guys and gals.


Solution

  • Add some NSLogs to see more numbers, such as stringToScan.length.

    "If targetRangeHeadword.length logs as 27 and targetRangeHeadword.location logs as 2496, how can I be getting the numbers the NSRangeException"

    Try to replace targetRangeHeadword.location with a magic number such as 2400 and NSLog it. Could it be that 2496 is the end of stringToScan ?

    -EDIT: I just noticed:

    Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString substringWithRange:]: Range {2634, 2147481013} out of bounds; string length 9309'
    

    Specifically Range {2634, 2147481013}, means one of your closing tags </> are not found.

    This number "2147481013" is an indicator that something was not found.