Objective-C“错误转换”使用 stringWithFormat 和 %d 的字符串/整数
我认为这是一个相对简单的问题,但我不太清楚发生了什么。
我有一个尝试使用 NSString 的 stringWithFormat 构建字符串的方法,
它看起来像这样:
NSString *line1 = [NSString stringWithFormat:@"the car is %d miles away", self.ma];
在上面的行中,“self.ma”应该是一个 int,但在我的例子中,我犯了一个错误,“self.ma”实际上指向一个 NSString。
所以,我明白该行应该读取,
NSString *line1 = [NSString stringWithFormat:@"the car is %@ miles away", self.ma];
但我的问题是第一个示例中的 %d 对我的 NSString 做了什么?
如果我使用调试器,我可以看到在一次情况下,“self .ma”等于“32444”,但不知何故%d将其转换为1255296。
我猜想32444的转换=>; 1255296 是某种类型的基数转换(十六进制到十进制或其他),但情况似乎并非如此。
知道 %d 对我的字符串做了什么吗?
TIA
I think this is a relatively simple question, but I don't precisely know what's happening.
I have a method that tries to build a string using NSString's stringWithFormat
It looks like this:
NSString *line1 = [NSString stringWithFormat:@"the car is %d miles away", self.ma];
In the above line "self.ma" should be an int, but in my case, I made an error and "self.ma" actually points to a NSString.
So, I understand that the line should read
NSString *line1 = [NSString stringWithFormat:@"the car is %@ miles away", self.ma];
but my question is what is the %d in the first example doing to my NSString?
If I use the debugger, I can see that in once case, "self.ma" equals "32444", but somehow the %d converts it to 1255296.
I would've guessed that the conversion of 32444 => 1255296 is some type of base-numbering conversion (hex to dec or something), but that doesn't appear to be the case.
Any idea as to what %d is doing to my string?
TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您实际上给它一个指向 NSString 的指针,因此当格式字符串需要整数时,它将给定的字节解释为 int。给出的是 NSString 在内存中的地址,因此打印出字符串的内存地址。
You are actually giving it a pointer to an NSString, so when the format string expects an integer, it interprets the given bytes as an int. What is given is the address to where the NSString is in memory, and so the memory address of the string is printed out.