Andrei
Andrei

Reputation: 1005

A String to int conversion returning 156112 instead of 1 in objective c

I have a NSMutableDictionary, with values. One of the values is an NSString "1".

I get it like this:

NSString *currentCount = [perLetterCount valueForKey:firstLetter];

then I convert it to an int:

int newInt = (int)currentCount;

And I display both like this:

NSLog(@"s: %@, i: %i", currentCount, newInt);

I get this as a result:

 c: 1, i: 156112

What am I doing wrong ?

Thank you

Upvotes: 2

Views: 104

Answers (3)

Joseph DeCarlo
Joseph DeCarlo

Reputation: 3278

Like mentioned above, you can use:

int newInt = [currentCount intValue];

However, if the string doesn't contain a number it returns a zero. This will be difficult if zero is a valid number in the string and it is also valid for the string to not have a number.

The way to get ints from strings when it's valid that the string doesn't contain one is:

NSScanner *scanner = [NSScanner scannerWithString:currentCount];

int newInt;
if (![scanner scanInt:&newInt]) {
    NSLog(@"Did not find integer in string:%@", currentCount);
}

Upvotes: 2

DRVic
DRVic

Reputation: 2491

What you are doing is converting a pointer (the address at which the string object currentCount's data is stored) to an integer. And it appears that integer is 156112.

To obtain the numeric value of an NSString you need to call one of its value methods:

[ currentCount intValue ]  or currentCount.intValue // for an int;
[ currentCount integerValue ] or currentCount.integerValue // for an NSInteger;
[ currentCount floatValue ] or currentCount.floatValue // for a float, and so on.

Upvotes: 7

Jimmy Luong
Jimmy Luong

Reputation: 1109

Try int newInt = currentCount.intValue instead.

Upvotes: 5

Related Questions