79

I want to convert string data to NSInteger.

Lucifer
  • 29,392
  • 25
  • 90
  • 143
The deals dealer
  • 1,006
  • 2
  • 8
  • 16

7 Answers7

146

If the string is a human readable representation of a number, you can do this:

NSInteger myInt = [myString intValue];
Aurum Aquila
  • 9,126
  • 4
  • 25
  • 24
  • 57
    I believe the right side of the expression should be [myString integerValue], no? – Kyle Clegg Nov 02 '12 at 20:56
  • `[myString intValue]` is a dark side ahaha – Alexander Perechnev Dec 09 '14 at 14:09
  • 4
    intValue returns an int, integerValue return an NSInteger. int is always an int type, but NSInteger changes types for the compiled device. There's more on that, but it's recommended to use NSInteger where ever possible. – Michael Ozeryansky Jan 11 '15 at 23:17
  • 2
    I'm disappointed. If you do something like `[@"Test" integerValue]` it will return `0` because `Test` is not a number. This is an unsafe way to do this. – eMdOS Sep 19 '17 at 13:11
78

[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 ).

Dilip Rajkumar
  • 7,006
  • 6
  • 60
  • 76
EtienneSky
  • 1,156
  • 10
  • 17
25

I've found this to be the proper answer.

NSInteger myInt = [someString integerValue];
pixelsize
  • 488
  • 5
  • 5
9
NSNumber *tempVal2=[[[NSNumberFormatter alloc] init] numberFromString:@"your text here"];

returns NULL if string or returns NSNumber

NSInteger intValue=[tempVal2 integerValue];

returns integer of NSNumber

2

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];
}
Enrico Cupellini
  • 447
  • 7
  • 14
1
int myInt = [myString intValue];
NSLog(@"Display Int Value:%i",myInt);
Amit Singh
  • 2,644
  • 21
  • 20
-3
NSString *string = [NSString stringWithFormat:@"%d", theinteger];
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Zverusha
  • 317
  • 3
  • 5