substringWithRange获取范围或索引超出范围的错误

时间:2012-07-19 04:41:21

标签: objective-c nsstring substring nsrange

首先是代码

// 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]);
}

使用测试字符串时,它会很顺利。

我的问题是当我使用数据中的字符串(其大小约为50k)时,它会转向错误......


于2012/07/19编辑

下面是字符串发生错误

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];

它可以匹配10个结果。

当运行substringWithRange:range行时,它会崩溃。

以下是错误日志。

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

1 个答案:

答案 0 :(得分:1)

您没有检查您实际 是否有效范围。来自class docs

  

如果其中一个捕获组未参与此特定匹配,则返回范围{NSNotFound,0}。

您需要在使用范围之前在代码中测试此条件,例如substringWithRange: