Search code examples
iosobjective-cnsstringsubstringnsrangeexception

range out of bounds size 4 objective c


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)];

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.