NSNumber LoopVar++在for循环中增加4而不是1
我很确定这个问题有一个非常简单的答案,我现在应该已经弄清楚了。由于我还没有这样做,所以我来找你,堆栈溢出蜂巢思维。
我期望下面的循环打印出从 0 到 5 的数字。相反,它只打印出 0 和 4。为什么 LoopNumber++ 将我的 NSNumber LoopNumber 增加 4 而不是 1?
NSNumber *LoopNumber;
for (LoopNumber=0; LoopNumber<=5; LoopNumber++) {
NSLog(@"%d",LoopNumber);
}
如果我将其更改为以下内容,它将完全按照我的预期工作。什么给?
for (int LoopNumber=0; LoopNumber<=5; LoopNumber++) {
我正在 XCode 3.2.1 中使用 SDK 3.1.2 玩弄一个 iPhone 项目。
I'm quite sure that this question has a very simple answer that I should have figured out by now. Since I haven't yet done so I come to you, stack overflow hive mind.
I expected the loop below to print out the numbers from 0 to 5. Instead it prints out only 0 and 4. Why does LoopNumber++ increment my NSNumber LoopNumber by 4 instead of by 1?
NSNumber *LoopNumber;
for (LoopNumber=0; LoopNumber<=5; LoopNumber++) {
NSLog(@"%d",LoopNumber);
}
If I change it to the following it works exactly as I expect. What gives?
for (int LoopNumber=0; LoopNumber<=5; LoopNumber++) {
I'm fooling around with an iPhone project in XCode 3.2.1, using SDK 3.1.2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSNumber 不是整数。它是一个数字的对象包装器,可以是整数。
变量 LoopNumber 实际上是一个指针,指向对象在内存中应该所在的位置。 LoopNumber 本身保存的只是一个内存地址,在你的机器上是 4 个字节长。当您执行 LoopNumber++ 时,您将在指针上 inzoking 指针 aritmatic,并且它会前进到四个字节后的下一个内存地址。您可以通过执行 sizeof(LoopNumber) 来查看这一点 - 这将在您的系统上返回 4。
您真正想要做的是使用常规整数,如下所示:
或者如果您确实需要使用 NSNumbers:
an NSNumber is not an integer. It is an object wrapper for a number which may be an integer.
The variable LoopNumber is actually a pointer to the location in memory where the object should be. All LoopNumber itself holds is a memory address, which on your machine is 4 bytes long. When you do LoopNumber++ you are inzoking pointer aritmatic on the pointer and it is advancing to the next memory address which is four bytes later. You can see this by doing a sizeof(LoopNumber) - that would return 4 on your system.
What you really want to do is use a regular integer like so:
or if you really need to use NSNumbers:
int 是本机类型。 NSNumber 是一个 Objective-C 类。在实际工作中使用 float 或 int。但是要将 int 放入集合中,您可以从 int 或 float 本机类型创建 NSNumber 对象。
int is native type. NSNumber is a Objective-C class. Use float or int when doing real work. But to put a int into a collection you can create an NSNumber object from the int or float native type.