Steven Jiang
Steven Jiang

Reputation: 1004

substringWithRange get Range or index out of bounds error

First is the code

// It's a test string 
NSString* aString =
    @",{id:\"bd\",name:\"ac\",latlng {lat:37.492488999999999,lng:127.014357}}";
// NSString *strRegex = @"latlng:\\ \\{(\\S*?)[^}]*\\}";
NSString *strRegex = @"latlng:\\{(\\S*?)[^}]*\\}";
NSRegularExpression* regEx = [NSRegularExpression
                                          regularExpressionWithPattern:strRegex
                                                               options:0
                                                                 error:NULL];
NSArray* matches = [regEx matchesInString:dataString
                                  options:0 
                                    range:NSMakeRange(0,[dataString length])];
NSInteger num=0;
for(NSTextCheckingResult* i in matches) {
    NSRange range = i.range;
    NSUInteger index = range.location; //the index you were looking for!
    //do something here
    num++;
    NSLog(@"%i",num);
    NSLog(@"index: %d",range.location);
    NSLog(@"length: %d", range.length);
    NSLog(@"%@",[aString substringWithRange:range]);
}

When use the test string, it goes well.

My problem is when I use a string from data (its size is about 50k), it turns to the error...


edited in 2012/07/19

Below is the string occurs error

NSError *error = nil;

NSString *urlString = [NSString stringWithFormat:@"http://maps.google.co.kr?q=%@&output=json", [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//#define NSKoreanEncoding 0x80000422
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]
                                     options:kNilOptions
                                       error:&error];
NSString *dataString = [[NSString alloc] initWithData:data
                                             encoding:NSKoreanEncoding];

It can match 10 results.

And when running the substringWithRange:range line it crashes.

Below is the error log.

2012-07-19 13:31:08.792 testView[6514:11c03] index: 649
2012-07-19 13:31:08.793 testView[6514:11c03] length: 46
2012-07-19 13:31:08.793 testView[6514:11c03] *** WebKit discarded an uncaught exception in the webView:shouldInsertText:replacingDOMRange:givenAction: delegate: <NSRangeException> -[__NSCFConstantString substringWithRange:]: Range or index out of bounds

Upvotes: 0

Views: 3863

Answers (1)

Conrad Shultz
Conrad Shultz

Reputation: 8808

You aren't checking that you actually got a valid range. From the class docs:

The range {NSNotFound, 0} is returned if one of the capture groups did not participate in this particular match.

You need to test for this condition in your code before just using the range in, e.g., substringWithRange:.

Upvotes: 1

Related Questions