我从下面的代码中收到以下错误,我不确定原因。
致命异常NSRangeException - [__ NSCFString replaceOccurrencesOfString:withString:options:range:]:范围{0,7}越界;字符串长度6
我想知道是否有人可以解释?
是否只需要新的NSRange变量来满足不同的字符串长度?
+(double)removeFormatPrice:(NSString *)strPrice {
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber* number = [currencyFormatter numberFromString:strPrice];
//cater for commas and create double to check against the number put
//through the currency formatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSMutableString *mstring = [NSMutableString stringWithString:strPrice];
NSRange wholeShebang = NSMakeRange(0, [mstring length]);
[mstring replaceOccurrencesOfString: [formatter groupingSeparator]
withString: @""
options: 0
range: wholeShebang];
//if decimal symbol is not a decimal point replace it with a decimal point
NSString *symbol = [[NSLocale currentLocale]
objectForKey:NSLocaleDecimalSeparator];
if (![symbol isEqualToString:@"."]) {
[mstring replaceOccurrencesOfString: symbol
withString: @"."
options: 0
range: wholeShebang]; // ERROR HERE
}
double newPrice = [mstring doubleValue];
if (number == nil) {
return newPrice;
} else {
return [number doubleValue];
}
}
答案 0 :(得分:2)
完成第一次替换操作后,字符串比构造范围时更短(您正在替换没有任何内容的字符)。原始初始化
NSRange wholeShebang = NSMakeRange(0, [mstring length]);
现在给出一个范围,其长度太大。例如:
NSMutableString* str = [NSMutableString stringWithString: @"1.234,5"];
NSRange allOfStr = NSMakeRange(0, [str length]);
[str replaceOccurrencesOfString: @"."
withString: @""
options: 0
range: allOfStr];
请注意,str
现在看起来像1234,5
,即它比当时短一个字符,范围已初始化。
因此,如果在现在太短的字符串上再次使用范围,则会得到索引超出范围的错误。您应该在将范围传递给第二个替换操作符之前重新初始化范围:
allOfStr = NSMakeRange(0, [str length]);
[str replaceOccurrencesOfString: @","
withString: @"."
options: 0
range: allOfStr];