jermel
jermel

Reputation: 2336

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) ?

Upvotes: 1

Views: 576

Answers (2)

Shamsudheen TK
Shamsudheen TK

Reputation: 31311

Instead of writing your own IBAction methods, just implement UITexFeild delegates.

To detect modifying text, implement shouldChangeCharactersInRange delegate.

To detect end editing , implement textFieldDidEndEditing delegate.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range      replacementString:(NSString *)string
{
  //write ur code here
  return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{

}

Upvotes: 1

Gabriele Petronella
Gabriele Petronella

Reputation: 108169

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.

Upvotes: 2

Related Questions