0

I am using:

cleanedDataCellR2C2 =  [cleanedDataCellR2C2 stringByReplacingOccurrencesOfString:@"," withString:@""];

and a whole bunch of similar satements to remove all keyboard characters from a textfield, except the digits.... - (the minus sign), + (the plus sign), as well as 0,1,2,3,4,5,6,7,8, and 9 numbers in a text field. The example above simply converts a comma in an NSString to a null value.

Hate to admit it, but in one project, I'm actually using about 80 statements -- one for every keyboard character except those shown above. Thee must be some easier way. What would you suggest to do this job?

SimplyKiwi
  • 12,376
  • 22
  • 105
  • 191
K17
  • 697
  • 3
  • 8
  • 26

2 Answers2

1

You could try using regex, here are a couple of examples:

Use regular expression to find/replace substring in NSString

NSRegularExpression: Replace url text with <a> tags

Replace occurences of string that contains any number

You can also check out http://regexkit.sourceforge.net/RegexKitLite/

Community
  • 1
  • 1
Sonny Parlin
  • 931
  • 2
  • 13
  • 28
1

The best solution is to not let them enter non-numeric data in the first place, if you can. Are you using a UITextField? If not, ignore the rest of this, but if so:

First, make your view controller is a UITextFieldDelegate, e.g.:

@interface MyViewController : UIViewController <UITextFieldDelegate>

and then later, in viewDidLoad:

self.myTextField.delegate = self;

Second, add a shouldChangeCharacterInRange to only allow the desired characters:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *nonNumeric = [[NSCharacterSet characterSetWithCharactersInString:@"+-0123456789"] invertedSet];

    if ([string rangeOfCharacterFromSet:nonNumeric].location == NSNotFound)
        return TRUE;
    else
        return FALSE;
}

Third, you might want to change your text field's keyboard to be for numeric data only, e.g. self.myTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation or UIKeyboardTypeDecimalPad or something like that.

Rob
  • 415,655
  • 72
  • 787
  • 1,044