关于iphone:检查NSString是否为整数

Checking if NSString is Integer

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
NSString is integer?

我正在寻找一个字符串是否只有数字。 基本上:

1
2
3
4
if (string is integer):
   #do whatever
else:
   #error

我该怎么做? 谢谢!


我用过[NSCharacterSet decimalDigitCharacterSet]。 绝对运作良好。

1
2
3
4
5
6
NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];

if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
// newString consists only of the digits 0 through 9
}


1
2
3
4
-(BOOL)isANumber:(NSString *)string{
    NSPredicate *numberPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES '^[0-9]+$'"];
    return [numberPredicate evaluateWithObject:string];
}