【问题标题】:Fatal Exception NSRangeException -[__NSCFString replaceOccurrencesOfString:withString:options:range:]: Range {N, N} out of bounds; string length N致命异常 NSRangeException -[__NSCFString replaceOccurrencesOfString:withString:options:range:]: Range {N, N} out of bounds;字符串长度 N
【发布时间】:2013-10-07 17:28:00
【问题描述】:

我从下面的代码中收到以下错误,我不知道为什么。

致命异常 NSRangeException -[__NSCFString replaceOccurrencesOfString:withString:options:range:]: 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];
    }
}

【问题讨论】:

  • 解释什么? 7 > 6 怎么算?

标签: ios objective-c cocoa-touch


【解决方案1】:

在完成第一次替换操作后,字符串比构建范围时的字符串短(您正在替换没有任何内容的字符)。原来的初始化

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

【讨论】:

  • 我认为这里的关键是字符串可能更小,也可能不会,但我需要这条线来满足两者。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-14
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
  • 2013-12-22
  • 1970-01-01
  • 2011-05-11
相关资源
最近更新 更多