16

在目标 c 中,我如何检查字符串/NSNumber 是整数还是 int

4

6 回答 6

39

如果您尝试确定 anNSString是否具有数值,请尝试使用NSNumberFormatter.

-(BOOL) stringIsNumeric:(NSString *) str {
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    NSNumber *number = [formatter numberFromString:str];
    [formatter release];
    return !!number; // If the string is not numeric, number will be nil
}
于 2010-08-13T06:10:23.297 回答
12

您可以在 NSString 上使用 intValue 方法:

NSString *myString = @"123";
[myString intValue]; // returns (int)123

这是它的 Apple 文档 - 如果它不是有效整数,它将返回 0:http: //developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html #//apple_ref/occ/instm/NSString/intValue

希望有帮助!

于 2010-08-13T04:01:39.010 回答
4

I've put this in my category NSString (Util).

- (BOOL) isInt {
    if ([self isEqualToString:@"0"])
        return YES;
    return (self.intValue != 0);
}
于 2013-04-09T01:28:16.760 回答
3

要检查 NSNumber 是否为整数,请尝试:

const char *t = [(NSNumber *)value objCType];
if (strcmp("i", t) == 0); // YES if integer
于 2010-08-13T04:02:26.180 回答
2

For NSString, if you use intValue/integerValue, there are certain cases which are not handled as it takes into consideration only the beginning the string.

For example @"bl3h" was not considered an integer but @" 3h" gave an output of 3

My solution for NSString:

Use :

NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:strName];

NSCharacterSet *numSet = [NSCharacterSet decimalDigitCharacterSet];

if([numSet isSupersetOfSet: charSet])
{
     // It is an integer (or it contains only digits)
}
于 2015-06-03T08:00:15.893 回答
0
if( [(NSString *)someString intValue] )
{ /* Contains an int fosho! */ }

if( [(NSNumber *)someNumber intValue] )
{ /* Contains an int wich is not 0.... :D */ }

您当然可以首先确定它是 NSString 还是 NSNumber 通过使用

[Object isKindOfClass:[NSString class]] 等等...

– boolValue – charValue – decimalValue – doubleValue – floatValue – intValue – integerValue – longLongValue – longValue – shortValue – unsignedCharValue – unsignedIntegerValue – unsignedIntValue – unsignedLongLongValue – unsignedLongValue – unsignedShortValue

are all methods of NSNumber to get its values. NSString got a few similar ones.

于 2010-08-13T07:15:27.227 回答