Reputation: 69
I am having strange problem. The following substring code crashes with
NSString *string4 = @"<p>some</p><img></img><p></p>end of the story":
[string4 substringWithRange:NSMakeRange(7, [string4 length] - 1)];
I assume the range is within the boundary but it still crashes. Any idea why this is happening ? The following is the error it showed.
* Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFConstantString substringWithRange:]: Range or index out of bounds' * First throw call stack: (0x1c92012 0x10cfe7e 0x1c91deb 0x1c6aaa4 0x2bbc 0xf51c7 0xf5232 0x443d5 0x4476f 0x44905 0x4d917 0x27c5 0x11157 0x11747 0x1294b 0x23cb5 0x24beb 0x16698 0x1beddf9 0x1bedad0 0x1c07bf5 0x1c07962 0x1c38bb6 0x1c37f44 0x1c37e1b 0x1217a 0x13ffc 0x24fd 0x2425) libc++abi.dylib: terminate called throwing an exception (lldb)
Upvotes: 1
Views: 3109
Reputation: 386018
The second argument to NSMakeRange
is the number of characters to include in the substring. Thus it must be no more than [string4 length] - 7
, because the starting location of the range is 7
. Try this:
NSString *string4 = @"<p>some</p><img></img><p></p>end of the story":
NSUInteger start = 7;
[string4 substringWithRange:NSMakeRange(start, [string4 length] - start - 1)];
Upvotes: 3
Reputation: 119041
NSMakeRange(7, [string4 length] - 1)
This range starts 7 characters from the beginning and finishes 6 characters after the end of the string.
A range is composed of the start location and the desired length from that location.
Upvotes: 6