objective-c - 字符串到 int 的转换返回 156112 而不是 objective-c 中的 1

标签 objective-c string integer type-conversion

我有一个带有值的 NSMutableDictionary。其中一个值是 NSString“1”。

我的理解是这样的:

NSString *currentCount = [perLetterCount valueForKey:firstLetter];

然后我将其转换为 int:

int newInt = (int)currentCount;

我像这样显示两者:

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

我得到这个结果:

 c: 1, i: 156112

我做错了什么?

谢谢

最佳答案

您所做的是将指针(字符串对象 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.

关于objective-c - 字符串到 int 的转换返回 156112 而不是 objective-c 中的 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10115367/

相关文章:

swift - 如何从一个范围内的数字插值到另一个范围内的相应值?

c++ - 有没有办法对从字符串 cpp 转换而来的整数执行算术

objective-c - 我可以释放在 block 运行之前使用它的 block 外部创建的对象吗?

c - C语言中如何连接字符串?

c++ - 最好的字符串搜索算法

c - (int) 转换如何作用于 char 数组和 char *?

java - 在 Java 中将整数四舍五入为特定整数

objective-c - 从主项目导入 constatnts 头文件到 Cocoa pod 文件

objective-c - 使用 @synthesized getter 有什么意义?

objective-c - 更新绑定(bind)到 NSArrayController 的表列