Reputation: 12003
For some reason this is tripping me up today.
I've got an NSString I'm trying to search using -rangeOfString:options:range:
and I keep getting this exception. What I'm doing:
I'm searching the string trying to find the next newline character after a certain character index (so, given an index i
, find the next occurrence of @"\n"
after that). I have i
, now I'm searching for the next newline like so (this is in an NSTextView
subclass)
NSRange untilReturn = [wholeString rangeOfString:@"\n" options:kNilOptions range:NSMakeRange(startLocation, [wholeString length] - 1)];
Where wholeText
is the whole text of the textView and startLocation
is i
.
But when I run this I get an out of bounds exception and I can't seem to figure out what's going wrong. Can someone lend a hand?
Upvotes: 0
Views: 2945
Reputation: 12003
It's simple! In my particular case, I was much better off using the method -lineRangeForRange:
. I'd totally forgotten about that API. So the code looks like the following:
NSRange lineRange = [wholeString lineRangeForRange:originalRange];
NSString *lineString = [wholeString substringWithRange:lineRange];
Upvotes: 0
Reputation: 410622
The second parameter to NSMakeRange
is the length (from the first parameter). Unless startLocation
is always 0 (and I assume it's not), your length is going to be too long. You actually want the second parameter to be [wholeString length] - startLocation
).
Upvotes: 2