views:

462

answers:

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);
...

-(IBAction)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
+31  A: 

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.

Carl Norum
in my .h file I am declaring "int *counterValue;" -- is that the problem?
jnunn
@jnunn, Yes. That is your problem. If you want a variable of type `int`, don't declare a pointer.
Carl Norum
that fixed it--thanks Carl
jnunn
+1 for accurate psychic debugging.
quixoto
Do int counterValue instead (no *).
Rudi
Haha, I knew what was happening as soon as I saw the question title. For some reason, creating pointers by mistake is incredibly common with programmers learning Objective-C.
Chuck
@Chuck, definitely. There's a lot of `*` getting flung around for people who came from programming Java all day. The bad part about this question is the OP didn't write what was actually in his code in his question.
Carl Norum
Nice Jedi Move dude!
Jordan