在Objective-C中,为什么增加4而不是1?

时间:2010-02-23 00:58:59

标签: iphone objective-c xcode

在Objective-C中,我有一个简单的代码块,每次按下按钮都会增加一个计数器。我的日志,甚至是界面的更新,都显示增量为4而不是1。这只是我格式化的显示问题(我正在使用%d)或其他我错过的东西?我的猜测在于“%d”,但我是Objective-C的新手,并不确定。 (注意,我也试过“counter + = 1;”,结果相同。

int counterValue = 0;
NSLog(@"Count at init: %d",counterValue);
...

-(IBAction)pushButton { 
    NSLog(@"Count (Pre-Push) = %d",counterValue);
    counterValue++;
    NSLog(@"Count (Post-Push) = %d",counterValue);
}

输出如下:

2010-02-20 18:39:39.125 My App[37536:207] Count at init:  0
2010-02-20 18:39:39.845 My App[37536:207] Count (Pre-Push) = 0
2010-02-20 18:39:39.846 My App[37536:207] Count (Post-Push) = 4
2010-02-20 18:39:40.165 My App[37536:207] Count (Pre-Push) = 4
2010-02-20 18:39:40.166 My App[37536:207] Count (Post-Push) = 8
2010-02-20 18:39:40.727 My App[37536:207] Count (Pre-Push) = 8
2010-02-20 18:39:40.728 My App[37536:207] Count (Post-Push) = 12

1 个答案:

答案 0 :(得分:43)

您展示的代码不应该这样做。我做了一个快速的程序来进行双重检查,我得到了预期的结果:

2010-02-22 17:04:35.787 app[68267:a0f] Count (Pre-Push) = 0
2010-02-22 17:04:35.790 app[68267:a0f] Count (Post-Push) = 1
2010-02-22 17:04:35.923 app[68267:a0f] Count (Pre-Push) = 1
2010-02-22 17:04:35.924 app[68267:a0f] Count (Post-Push) = 2

我最好的猜测是,您使用另一个counterValue类型的变量隐藏了int *,这使得+增加了sizeof(int)而不是1。