tags:

views:

97

answers:

4

Hello.

In objective c, how can i check if a string/NSNumber is an integer or int

+1  A: 

You can use the intValue method on NSString:

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

Here is the Apple documentation for it - it will return 0 if it's not a valid integer: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/intValue

Hope that helps!

codykrieger
How can i find if a variable is a string?
Daniel
As in, you want to check and see if some user input is just a plain old string or a number? Like I said above, intValue returns 0 for when an NSString is not a valid integer. Say you're getting info from a UITextView - [[myTextView text] intValue] would return a valid int if possible, or 0 if it can't be validated as an int.
codykrieger
Well see the problem is. Sometimes the user will not enter any input. because it is not required. And since i'm using an array and grabbing the object from it. I'm getting *** -[NSCFArray objectAtIndex:]: index (3) beyond bounds (3) i need to check if the array is valid somehow?
Daniel
What if the string represents the actual integer value 0?
dreamlax
Could you maybe post some of your code so we can get a better feel for what's going on?
codykrieger
A: 

To check if a NSNumber if an integer try:

const char *t = [(NSNumber *)value objCType];
if (strcmp("i", t) == 0); // YES if integer
Kevin Sylvestre
A: 

If you're trying to determine whether or not an NSString has a numeric value or not, try using 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
}
anshuchimala
A: 
if( [(NSString *)someString intValue] )
{ /* Contains an int fosho! */ }

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

You can ofcourse first determine whether its a NSString or NSNumber by using

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

– 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.

Antwan van Houdt