Objective-C“错误转换”使用 stringWithFormat 和 %d 的字符串/整数

发布于 2024-08-31 16:46:18 字数 665 浏览 1 评论 0原文

我认为这是一个相对简单的问题,但我不太清楚发生了什么。

我有一个尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丶情人眼里出诗心の 2024-09-07 16:46:18

您实际上给它一个指向 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文