NSRange `replaceCharactersInRange` crashing app after backspace & entry of new character
<p>I have one textfield, &amp; use <code>shouldChangeCharactersInRange</code> method to get value.</p>

<p>Here is my Code:</p>

<pre><code>- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSLog(@"Pressing : %@\n", string);
    NSMutableString *text = [NSMutableString stringWithString:textField.text];

    NSLog(@"length: %lu", (unsigned long)range.length);
    NSLog(@"location: %lu\n", (unsigned long)range.location);
    NSLog(@"before text: %@", textField.text);

    [text replaceCharactersInRange:range withString:string];
    NSLog(@"After replacement , Text: %@\n\n", text);

    // My work..

    return YES;
}
</code></pre>

<p>I first add character 'T' to textfield, it works fine ..</p>

<pre><code>2016-03-02 10:06:23.162 MyTextFieldApp[12006:4323645] Pressing : T
2016-03-02 10:06:23.163 MyTextFieldApp[12006:4323645] length: 0
2016-03-02 10:06:23.163 MyTextFieldApp[12006:4323645] location: 0
2016-03-02 10:06:23.163 MyTextFieldApp[12006:4323645] before text: 
2016-03-02 10:06:23.163 MyTextFieldApp[12006:4323645] After replacement , Text: T
</code></pre>

<p>Then, I backspace it to remove character, that also works fine..</p>

<pre><code>2016-03-02 10:06:30.979 MyTextFieldApp[12006:4323645] Pressing : 
2016-03-02 10:06:30.980 MyTextFieldApp[12006:4323645] length: 1
2016-03-02 10:06:30.980 MyTextFieldApp[12006:4323645] location: 0
2016-03-02 10:06:30.980 MyTextFieldApp[12006:4323645] before text: T
2016-03-02 10:06:30.981 MyTextFieldApp[12006:4323645] After replacement , Text: 
</code></pre>

<p>But, when I am going to add new character then, it crash on replaceString.. </p>

<blockquote>
  <p>Note: This time, Range Gives length 0 &amp; location 1, while first time also when i am adding T to empty textfield, it gives length 0 as well as location 0.</p>
</blockquote>

<pre><code>2016-03-02 10:07:02.158 MyTextFieldApp[12006:4323645] Pressing : T
2016-03-02 10:07:02.158 MyTextFieldApp[12006:4323645] length: 0
2016-03-02 10:07:02.159 MyTextFieldApp[12006:4323645] location: 1
2016-03-02 10:07:02.159 MyTextFieldApp[12006:4323645] before text: 
2016-03-02 10:07:02.159 MyTextFieldApp[12006:4323645] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds'
</code></pre>

<p>I can't detect where is the problem?</p>