Oliver
Oliver

Reputation: 403

ObjC/Cocoa NSRange: Range or index out of bounds

I'm trying to find an answer to a problem that's been puzzling me since last night.

NSRange searchRange.location = 0;
NSRange searchRange.length = [string length]; // > 2000 characters long
NSString *substring = @"substring"; // Occurs within string several times

NSRange substringRange = [string rangeOfString:substring options:NSCaseInsensitiveSearch range:searchRange];

// Some code here. Create substring and add it to array.

// Move the search range on
searchRange.location = substringRange.location + substringRange.length;

// fails
substringRange = [string rangeOfString:substring options:NSCaseInsensitiveSearch range:searchRange];

The first [string rangeOfString...] method gets called without a hitch, but the second call results in the following error:

* -[__NSCFString rangeOfString:options:range:locale:]: Range or index out of bounds

From what I can tell, the problem is caused by the assignment of the new value to searchRange.location -- removing that statement results in a successful second call to the method. Looking at the debugger, the values seem to be as predicted -- nothing outside of range -- and I'm left screaming at the monitor.

It's just simple addition... isn't it?

Upvotes: 1

Views: 1121

Answers (1)

Wain
Wain

Reputation: 119031

The problem is that you modify the location but you don't modify the length. The result is a range that is too long. The solution is to reduce the length by the same amount as you increase the location.

Upvotes: 7

Related Questions