Sunday, April 3, 2011

NSString is integer?

How to check if the content of a NSString is an integer value? Is there any readily available way?

There got to be some better way then doing something like this:

- (BOOL)isInteger:(NSString *)toCheck {
  if([toCheck intValue] != 0) {
    return true;
  } else if([toCheck isEqualToString:@"0"]) {
    return true;
  } else {
    return false;
  }
}
From stackoverflow
  • You could use the -intValue or -integerValue methods. Returns zero if the string doesn't start with an integer which is a bit of a shame as zero is a valid value for an integer...

    A better option might be to use [NSScanner scanInt:] which returns a BOOL indicating whether or not it found a suitable value.

    carlosb : Right on! A simple [[NSScanner scannerWithString:value] scanInt:nil] will check if "value" has an integer value. Thanks!
  • Something like this:

    NSScanner* scan = [NSScanner scannerWithString:toCheck]; 
    int val; 
    return [scan scanInt:&val] && [scan isAtEnd];
    

0 comments:

Post a Comment