NSInteger multiples of 4 dilemma

Discussion in 'iOS Programming' started by nomar383, May 11, 2009.

  1. nomar383 macrumors 65816

    nomar383

    Joined:
    Jan 29, 2008
    Location:
    Rexburg, ID
    #1
    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?

    Code:
    #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
    
     
  2. Guiyon macrumors 6502a

    Joined:
    Mar 19, 2008
    Location:
    North Shore, MA
    #2
    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.
     
  3. nomar383 thread starter macrumors 65816

    nomar383

    Joined:
    Jan 29, 2008
    Location:
    Rexburg, ID
    #3
    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.
     
  4. mccannmarc macrumors 6502

    mccannmarc

    Joined:
    Aug 15, 2008
    Location:
    Manchester, UK
    #4
    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
     

Share This Page