I want to convert string
data
to NSInteger
.
Asked
Active
Viewed 9.7k times
79

Lucifer
- 29,392
- 25
- 90
- 143

The deals dealer
- 1,006
- 2
- 8
- 16
-
2If you google it you can easily get the answer in the first hit itself – KingofBliss Jan 25 '11 at 09:32
-
22You should accept answers to your questions. – BoltClock Jan 25 '11 at 12:57
-
3At what point do abandoned questions like this get "auctioned" off for the community to buy with reputation points.... hmmm :-) – Norman H May 15 '12 at 13:50
-
16@KingOfBliss I googled it and my first hit was this post :) – Stephan Celis Nov 02 '12 at 08:40
-
2@StephanCelis Before this, it was some other post. Now this ranked up based on most number of views :) – KingofBliss Nov 06 '12 at 09:39
7 Answers
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
-
57I believe the right side of the expression should be [myString integerValue], no? – Kyle Clegg Nov 02 '12 at 20:56
-
-
4intValue 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
-
2I'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
-3
NSString *string = [NSString stringWithFormat:@"%d", theinteger];