Pergunta

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)];
Foi útil?

Solução

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.

Outras dicas

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)];
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top