Search code examples
iosios5uitextfielduitextfielddelegate

ios edit textfield infinite loop


Problem: I have a method that handles editingChanged events and another method that updates my textfields from an object model. The problem is that if I modify the text of the field that sent the event, it triggers editingChanged again and I enter an infinite loop (only in ios 5)!

Example:

- (IBAction)updateFields:(UITextField *)sender {
    if ([self myCustomValidation:sender]) {
        ... //update model
        //call another method that essentially does this
        field1.text = @"someformatted text"; //causes infinite loop if any field == sender
        field2.text = @"some more text";
    }
}

How do you work around this issue (without having to pass sender to all methods that send setText: messages) ?


Solution

  • Consider implementing the UITextFieldDelegate's method textField:shouldChangeCharactersInRange:replacementString: instead of registering for the editingChanged control event.

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        ... //update model
        //call another method that essentially does this
        field1.text = @"someformatted text";  //causes infinite loop any field == sender
        field2.text = @"some more text";
        return YES; // or NO, depending on you actions
    }
    

    According to the documentation it should serve your purposes

    The text field calls this method whenever the user types a new character in the text field or deletes an existing character.