Search code examples
ios5ibaction

iOS5 > app freezes when Editing Changed function is fired on UITextField


I am firing the following function on "Editing Changed" on a UITextField. The purpose is to format the number as the user types in. It is working fine on iOS6+ but the app freezes on iOS5 just as the user types the first character in that field. Can somebody help to find out what might be the issue with this 3 line function. It freezes on the third line where NSNumberFormatter is being used.

-(IBAction)formatNumber:(UITextField*)sender
{
if(sender.text!=NULL)
{
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
NSString *currentVal=[[sender.text componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];

sender.text=[NSNumberFormatter localizedStringFromNumber:[NSNumber numberWithInt:[currentVal intValue]]
                                 numberStyle:NSNumberFormatterDecimalStyle];
}
}

Solution

  • The problem is that event UIControlEventEditingChanged is called every time something is changed in the sender.

    By setting new text:

    sender.text=[NSNumberFormatter localizedStringFromNumber:[NSNumber numberWithInt:[currentVal intValue]]
                                 numberStyle:NSNumberFormatterDecimalStyle];
    

    you are actually sending event UIControlEventEditingChanged again and again, causing endless recursion.