Peter Walke
Peter Walke

Reputation: 2518

Why is my button clicked event being called 4 times?

Probably a noob question, but I'm trying to write a simple iPhone app that increments a label by the number of times a button is clicked. I have the following code:

#import "Controller.h"

int *i = 0;
@implementation Controller 
- (IBAction)buttonClicked:(id)sender {      
    NSString *numTimesClicked = [NSString stringWithFormat:@"%d",i++    ];      
    myLabel.text    = numTimesClicked;      
}
@end

When I click the button, the label updates in multiples of 4 (4,8,12,16, etc). What might I be doing wrong here?

Upvotes: 2

Views: 118

Answers (1)

Chuck
Chuck

Reputation: 237060

Look at the definition of i:

int *i = 0;

i isn't an integer — it's a pointer to an integer. The size of an int is 4 bytes on your architecture, so the pointer increments by 4 (which would be the address of the next int in an array of ints). You want to declare it as just int i = 0.

Upvotes: 10

Related Questions