2012-07-19 2 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년 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 

답변

1

당신은 당신이 실제로 유효한 범위를 가지고 있음을 확인하지 않습니다. class docs에서 : 캡처 그룹 중 하나가이 특정 경기에 참여하지 않은 경우

범위 {NSNotFound 0} 반환됩니다.

범위를 사용하기 전에 코드에서이 조건을 테스트해야합니다 (예 : substringWithRange:).

+0

올바른 범위 값을 얻을 수 있습니다. 'substringWithRange' 라인에서만 오류가 발생합니다. 두 종류의 문자열로 테스트했습니다. 하나는 슬램이며 오류가 없습니다. 다른 하나는 큰 문자열이며 회전합니다 'substringWithRange' 라인에 오류가 있습니다. –

+0

@StevenJiang 그게 가능한지 모르겠습니다. '[aString length]'의 출력과 잘못된 'range'를 게시 할 수 있습니까? –

+0

나는 문제를 발견했다. 나는 어리석은 실수를했다.'aString'에'dataString'의 범위를 사용합니다 ... 도와 줘서 고맙습니다 ~~^- ^ –