Convert NSString to NSInteger?

IphoneNsstringNsinteger

Iphone Problem Overview


I want to convert string data to NSInteger.

Iphone Solutions


Solution 1 - Iphone

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

NSInteger myInt = [myString intValue];

Solution 2 - Iphone

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

Solution 3 - Iphone

I've found this to be the proper answer.

NSInteger myInt = [someString integerValue];

Solution 4 - Iphone

NSNumber *tempVal2=[[[NSNumberFormatter alloc] init] numberFromString:@"your text here"];

> returns NULL if string or returns NSNumber

NSInteger intValue=[tempVal2 integerValue];

> returns integer of NSNumber

Solution 5 - Iphone

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];
}

Solution 6 - Iphone

int myInt = [myString intValue];
NSLog(@"Display Int Value:%i",myInt);

Solution 7 - Iphone

NSString *string = [NSString stringWithFormat:@"%d", theinteger];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThe deals dealerView Question on Stackoverflow
Solution 1 - IphoneAurum AquilaView Answer on Stackoverflow
Solution 2 - IphoneEtienneSkyView Answer on Stackoverflow
Solution 3 - IphonepixelsizeView Answer on Stackoverflow
Solution 4 - Iphoneuser4993619View Answer on Stackoverflow
Solution 5 - IphoneEnrico CupelliniView Answer on Stackoverflow
Solution 6 - IphoneAmit SinghView Answer on Stackoverflow
Solution 7 - IphoneZverushaView Answer on Stackoverflow