Convert NSString to NSInteger?
Asked Answered
S

7

80

I want to convert string data to NSInteger.

Stylography answered 25/1, 2011 at 8:52 Comment(5)
If you google it you can easily get the answer in the first hit itselfFarah
You should accept answers to your questions.Nibelungenlied
At what point do abandoned questions like this get "auctioned" off for the community to buy with reputation points.... hmmm :-)Walloping
@KingOfBliss I googled it and my first hit was this post :)Frowzy
@StephanCelis Before this, it was some other post. Now this ranked up based on most number of views :)Farah
A
147

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

NSInteger myInt = [myString intValue];
Actinoid answered 25/1, 2011 at 8:56 Comment(4)
I believe the right side of the expression should be [myString integerValue], no?Margarine
[myString intValue] is a dark side ahahaWomanizer
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.Mackler
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.Bork
C
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 ).

Callean answered 25/1, 2011 at 9:48 Comment(1)
simple and util tip. :)Burbage
C
25

I've found this to be the proper answer.

NSInteger myInt = [someString integerValue];
Carlenacarlene answered 23/12, 2013 at 18:6 Comment(0)
S
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

Saiz answered 26/11, 2015 at 9:48 Comment(0)
C
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];
}
Chiropteran answered 24/11, 2016 at 14:12 Comment(0)
Q
1
int myInt = [myString intValue];
NSLog(@"Display Int Value:%i",myInt);
Quoin answered 18/3, 2013 at 8:23 Comment(0)
B
-3
NSString *string = [NSString stringWithFormat:@"%d", theinteger];
Branen answered 25/3, 2015 at 11:19 Comment(1)
He asked for the reverse of this.Dodecahedron

© 2022 - 2024 — McMap. All rights reserved.