iosobjective-cindexoutofboundsexceptioninvalidargumentexception

ReplacingCharactersInRange out of bounds error


I have a textfield that accepts numbers and I am trying to replace the 8th character in the string with a "."

if(self.txtQty.text.length >= 8){
    NSRange range = NSMakeRange(8,1);
    self.txtQty.text = [self.txtQty.text stringByReplacingCharactersInRange:range withString:@"."];
}

-Example-
1234567.90

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds' *** First throw call stack:

I keep receiving this error.


Solution

  • The range {8,1} means you are trying to access the 9th character. But your if check only verifies if the string has 8 or more characters. So if the string is exactly 8 characters long then you will get that error.

    Update your if check to:

    if (self.txtQty.text.length > 8) {
    

    Or possibly your if check is correct and the range should be changed from {8,1}, to {7,1} to replace the 8th character.

    Which of those two changes you make depends on your goal (to change the 8th or 9th character).


    To help visualize the range, I'll attempt a bit of a drawing:

    Some string, its indexes, and range {8,1}:

     1 2 3 4 5 6 7 8 9 0   <-- The string
    | | | | | | | | | | |
    0 1 2 3 4 5 6 7 8 9 1  <-- Its indexes
                        0
                    ***    <-- Area for {8,1}
    

    Here you can see that the range {8,1} is getting the 9th character.