2012-07-19 23 views
0

首先是代碼substringWithRange獲得範圍或索引越界錯誤

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

你不檢查你實際上的有效範圍。從class docs

如果其中一個捕獲組未參與此特定匹配,則返回範圍{NSNotFound,0}。

在使用範圍之前,您需要在代碼中測試此條件,例如substringWithRange:

+0

我可以拿到合適的範圍values.Only輪流在'substringWithRange' line.I二種string.One的測試誤差是花冤枉錢,它沒有和error.The另一種是一個大的字符串,它變成以'substringWithRange'行錯誤 – 2012-07-19 05:41:02

+0

@StevenJiang我不明白這是可能的。你能發佈'[aString length]'的輸出和有問題的'range'嗎? – 2012-07-19 05:46:23

+0

我發現了這個問題......我犯了一個愚蠢的錯誤......使用'aString'上'dataString'的範圍......感謝您的幫助~~^- ^ – 2012-07-19 07:41:51