Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring out of bounds exception with NSMakeRange

When looping through, making a substring of every letter in a NSString, this exception is thrown:

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

Code:

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

Called from here:

- (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 declaration is: @property (copy) NSString *text;

The exception is thrown when i = 13172 and content.length = 26344.

The code is run in a background thread, but content is not accessed by any other thread.

Thank you for any help!

like image 416
mfaerevaag Avatar asked Dec 16 '22 09:12

mfaerevaag


1 Answers

The problem was:

I though the NSMakeRange took the parameters index-from and index-to. It actually takes index-from and length of substring, so when the iteration passed the half way mark (see question), it goes out of bounds.

Silly...

like image 112
mfaerevaag Avatar answered Dec 23 '22 18:12

mfaerevaag