1

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)

RealityOD
  • 69
  • 2
  • 8
  • at the end of first line, is it a colon (:)? It should be semicolon (;)? – ShinTakezou Jun 04 '13 at 06:54
  • 1
    Your range is bigger than your string. `substringWithRange:` will raise an exception if you try to get a substring outside the string. The arguments to `NSMakeRange` are starting point and length, not start and end. – Greg Jun 04 '13 at 06:56

2 Answers2

6

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.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • Arghh, my bad. I thought second parameter is the end index. I wasted a lot of time on this. Thanks a lot! – RealityOD Jun 04 '13 at 06:55
3

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)];
rob mayoff
  • 375,296
  • 67
  • 796
  • 848