使用NSMakeRange的子串超出边界异常

时间:2013-06-13 08:10:39

标签: objective-c macos substring

循环时,在NSString中创建每个字母的子字符串,抛出此异常:

-[__NSCFString substringWithRange:]: Range or index out of bounds

代码:

- (void) analyzeContent:(NSString *)content
{
    content = [content uppercaseString];
    for (int i = 1; i < content.length; i++) {
        NSString *ch = [content substringWithRange:NSMakeRange(i-1, i)]; // <-- exception
    }
}

从这里打来:

- (IBAction)analyze:(id)sender
{
    if (!self.text) {
        NSString *path = [[NSBundle mainBundle] pathForResource:CYPHERTEXT_FILE
                                                         ofType:@"txt"];
        self.text = [NSString stringWithContentsOfFile:path
                                              encoding:NSUTF8StringEncoding
                                                 error:NULL];
    }

    [self.progIndicator setHidden:NO];
    [self.progIndicator startAnimation:nil];
    dispatch_queue_t queue = dispatch_queue_create("queue", 0);
    dispatch_async(queue, ^{

        [self.analyzer analyzeContent:self.text];

        // When finished update UI
        dispatch_sync(dispatch_get_main_queue(), ^{
            [self.progIndicator setHidden:YES];
            [self.progIndicator stopAnimation:nil];
        });
    });
}

text - 属性声明为:@property (copy) NSString *text;

i = 13172content.length = 26344时会抛出异常。

代码在后台线程中运行,但任何其他线程都不会访问content

感谢您的帮助!

2 个答案:

答案 0 :(得分:9)

问题是:

我虽然NSMakeRange采用了参数index-from和index-to。它实际上需要从子串的索引和长度,所以当迭代通过中间标记(见问题)时,它超出了界限。

...傻

答案 1 :(得分:3)

您的代码:

for (int i = 1; i < content.length; i++) {
            NSString *ch = [content substringWithRange:NSMakeRange(i-1, i)]; // <-- exception
        }

最初i = 1,然后需要2,3,4,5,6 ....并崩溃

尝试这样,

NSString *ch = [content substringWithRange:NSMakeRange(i-1, 1)];