开发者

In Objective-C, why does this increment by 4 instead of 1?

In Objective-C, I have a simple block of code that increments a counter each time a button is pushed. My logs, and even updates to the interface, are showing an increment of 4 instead of one. Is this just a display issue with my formatting (I'm using %d) or something else I'm missing? My guess lies with the "%d" but I'm new to Objective-C and not sure. (Note, I also tried "counter += 1;" with the same result.

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

-(IBActio开发者_StackOverflown)pushButton { 
    NSLog(@"Count (Pre-Push) = %d",counterValue);
    counterValue++;
    NSLog(@"Count (Post-Push) = %d",counterValue);
}

The output is as follows:

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


The code you're showing sure shouldn't do that. I made quick program to doublecheck, and I get the expected results:

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

My best guess is that you have shadowed counterValue with another variable of type int *, which is making the + increment by sizeof(int) instead of by 1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜