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!
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With