在目标c中返回156112而不是1的String转换为int转换

And*_*rei 2 string integer objective-c type-conversion

我有一个带有值的NSMutableDictionary.其中一个值是NSString"1".

我这样得到:

NSString *currentCount = [perLetterCount valueForKey:firstLetter];
Run Code Online (Sandbox Code Playgroud)

然后我将它转换为int:

int newInt = (int)currentCount;
Run Code Online (Sandbox Code Playgroud)

我这样显示:

NSLog(@"s: %@, i: %i", currentCount, newInt);
Run Code Online (Sandbox Code Playgroud)

我得到了这个结果:

 c: 1, i: 156112
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么 ?

谢谢

DRV*_*Vic 7

您正在做的是将指针(存储字符串对象currentCount的数据的地址)转换为整数.看来整数是156112.

要获取NSString的数值,您需要调用其值方法之一:

[ 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.
Run Code Online (Sandbox Code Playgroud)


Jim*_*ong 5

试试吧int newInt = currentCount.intValue.