Question

I get a value from a TextField and I need to check if there's a number in it. Whether it's a float or an integer doesn't really matter, but definitely a "Number"

How can I catch this?

This is what I'm doing so far - even if the obj is 123 (actually a number), the condition is false, so I can't get into the if. I already tried NSValue and Data, but with the same results.

id obj = self.textArea.text;

if ([obj isKindOfClass:[NSNumber class]]) {
    self.weight = [NSNumber numberWithFloat:([self.textArea.text floatValue])];
Était-ce utile?

La solution

The text of a text field will ALWAYS be a NSString since that is how the class was designed.

Your task, then, is to convert it into a NSNumber. The best way to do this is to use a number formatter like this:

NSNumberFormatter *formatter = [NSNumberFormatter new];
self.weight = [formatter numberFromString:self.textArea.text];
if (!self.weight) {
    // No valid number was found.
}

Autres conseils

You cant use floatValue since it will return 0.0 if there is either a 0 or no number at all. You cant use NSNumberFormatter as suggested by Inafziger if there are non number chars in the textfield.

Use:

NSCharacterSet *numberSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
NSRange numberRange = [self.textArea.text rangeOfCharacterFromSet:numberSet];
if (numberRange.location == NSNotFound) {
    NSLog(@"no");
} else {
    NSLog(@"yay");
}

Use a regular expression to test the value, then once you know it is a number you can do whatever else you need to.

NSError *error = NULL;
NSString *pattern = @"^[0-9]*\.?[0-9]+$"
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive erro:&error];
NSUInteger matches = [regex numberOfMatchesInString:self.textarea.text options:0 range:NSMakeRange(0, [self.textarea.text length])];
if (matches > 0)
{
     // do whatever you need to do now that you know it's a number
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top