【问题标题】:substringWithRange get Range or index out of bounds errorsubstringWithRange 获取范围或索引超出范围错误
【发布时间】:2012-07-19 04:41:21
【问题描述】:

首先是代码

// 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 年 7 月 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

【问题讨论】:

    标签: objective-c nsstring substring nsrange


    【解决方案1】:

    你并没有检查你实际上得到一个有效的范围。来自class docs

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

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

    【讨论】:

    • 我可以得到正确的范围值。仅在substringWithRange 行出现错误。我用两种字符串进行了测试。一种是samller,它没有错误。另一种是大字符串,它在substringWithRange 行上变成错误
    • @StevenJiang 我不明白这怎么可能。你能发布[aString length]的输出和冒犯的range吗?
    • 我找到了问题...我犯了一个愚蠢的错误...使用dataStringaString的范围...感谢您的帮助~~ ^-^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    相关资源
    最近更新 更多