The deals dealer
The deals dealer

Reputation: 1016

Convert NSString to NSInteger?

I want to convert string data to NSInteger.

Upvotes: 80

Views: 98102

Answers (7)

Enrico Cupellini
Enrico Cupellini

Reputation: 445

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

Upvotes: 2

user4993619
user4993619

Reputation:

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

returns NULL if string or returns NSNumber

NSInteger intValue=[tempVal2 integerValue];

returns integer of NSNumber

Upvotes: 9

Zverusha
Zverusha

Reputation: 317

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

Upvotes: -3

pixelsize
pixelsize

Reputation: 488

I've found this to be the proper answer.

NSInteger myInt = [someString integerValue];

Upvotes: 25

Amit Singh
Amit Singh

Reputation: 2644

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

Upvotes: 1

EtienneSky
EtienneSky

Reputation: 1156

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

Upvotes: 78

Aurum Aquila
Aurum Aquila

Reputation: 9126

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

NSInteger myInt = [myString intValue];

Upvotes: 147

Related Questions