Question

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)];
Was it helpful?

Solution

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.

OTHER TIPS

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)];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top