Convert NSString to NSInteger?
I want to convert string
data
to NSInteger
.
If the string is a human readable representation of a number, you can do this:
NSInteger myInt = [myString intValue];
[myString intValue]
returns a cType "int"
[myString integerValue]
returns a NSInteger
.
In most cases I do find these simple functions by looking at apples class references, quickest way to get there is click [option] button and double-click on the class declarations (in this case NSString ).
I've found this to be the proper answer.
NSInteger myInt = [someString integerValue];
NSNumber *tempVal2=[[[NSNumberFormatter alloc] init] numberFromString:@"your text here"];
returns NULL if string or returns NSNumber
NSInteger intValue=[tempVal2 integerValue];
returns integer of NSNumber
this is safer than integerValue:
-(NSInteger)integerFromString:(NSString *)string
{
NSNumberFormatter *formatter=[[NSNumberFormatter alloc]init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *numberObj = [formatter numberFromString:string];
return [numberObj integerValue];
}