PDA

View Full Version : NSInteger multiples of 4 dilemma




nomar383
May 11, 2009, 07:14 PM
Okay, all I am trying to do is setup a counter that will add 1 everytime a button is pressed on the iPhone screen. I have two buttons total, both execute the "buttonPressed" method. If I do a "+= 1" on overallCount as a local variable it's fine. If I do a "+= 1" as in the code below, overallCount in increased to 4, then 8, then 12, and so on. What the heck am I doing wrong?

#import <UIKit/UIKit.h>

@interface RL_GLViewController : UIViewController {
IBOutlet UIButton *leftButton;
IBOutlet UIButton *rightButton;
NSInteger *overallCount;
}

@property(nonatomic, retain) IBOutlet UIButton *leftButton;
@property(nonatomic, retain) IBOutlet UIButton *rightButton;
@property(nonatomic, assign) NSInteger *overallCount;


-(IBAction) buttonPressed:(id) sender;

@end

#import "RL_GLViewController.h"


@implementation RL_GLViewController

@synthesize leftButton;
@synthesize rightButton;
@synthesize overallCount;

-(IBAction) buttonPressed:(id) sender{

overallCount += 1;
NSLog(@"%d", overallCount);

}


- (void)dealloc {
[leftButton dealloc];
[rightButton dealloc];
[super dealloc];
}

@end



Guiyon
May 11, 2009, 07:21 PM
NSInteger is a primitive, not an object! What you are really doing is incrementing the address that the NSInteger* is pointing at. Since NSInteger is 4 bytes long, each time you increment it the compiler assumes that, since it's a pointer, you want to jump ahead to the next NSInteger in memory which is why you are getting multiples of 4. Just remove the '*' when you are declaring NSInteger and you should be all set.

nomar383
May 11, 2009, 08:00 PM
I thought it might be reporting the address since when I used "double" instead of "NSInteger" it was multiples of 8. I should have known I didn't need the "*" lol. Thanks!

EDIT: Yeah, that totally fixed it. Counts by 1 now. I thought NSInteger was an object for some reason. Objective-C takes some getting used to.

mccannmarc
May 12, 2009, 03:41 AM
I thought it might be reporting the address since when I used "double" instead of "NSInteger" it was multiples of 8. I should have known I didn't need the "*" lol. Thanks!

EDIT: Yeah, that totally fixed it. Counts by 1 now. I thought NSInteger was an object for some reason. Objective-C takes some getting used to.

The easiest and quickest way to find out if you're unsure is to right click the type in question and select 'jump to definition' It will take you to the header file where the type is defined and you will be able to see exactly what it is you are dealing with