2

I have an NSString of length 4. Logically, this should work, and expYear does, but expMonth throws an out of bounds exception?

expYear = [expDate substringWithRange:NSMakeRange(0, 2)];
expMonth = [expDate substringWithRange:NSMakeRange(2, 3)];
Wain
  • 118,658
  • 15
  • 128
  • 151
dsuma
  • 1,000
  • 2
  • 9
  • 30
  • Read the docs for `NSMakeRange`. – rmaddy Feb 06 '14 at 15:44
  • 3
    You are obviously super helpful – dsuma Feb 06 '14 at 16:26
  • 1
    I was serious. For a question like this all you needed to do was read the reference docs for `NSMakeRange` and you would have seen what the 2nd parameter means. Given the number of down votes, others seem to agree with me. The answer you accepted basically repeats what is in the documentation. – rmaddy Feb 06 '14 at 16:32

2 Answers2

11

A range is a location and a length, not a start and end position.

typedef struct _NSRange {
    NSUInteger location;
    NSUInteger length;
} NSRange;

So with a start location of 2 and a length of 3 you overrun the end.

Change the range based on the correct specification.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • You don't say whether you do, but you should also have a length check before running this code. – Wain Feb 06 '14 at 15:42
4

The range doesn't mean from let's say 2 to 3 it's say start from 2 and go next 3 indexes so in this example you end up with 2-5, so this line is out of bounds:

expMonth = [expDate substringWithRange:NSMakeRange(2, 3)];
Greg
  • 25,317
  • 6
  • 53
  • 62