Question

I am very new to Objective-c and probably really easy to solve but couldnt find an answer anywhere....

I am trying to add +1 to a variable every time the user clicks on the button but instead of adding +1 it adds +4

- (IBAction)addNewSet:(UIButton *)sender {
    NSLog(@"%i",_sliderTag);
    _sliderTag += 1;
   NSLog(@"ADD NEW    %i",_sliderTag);
}

_sliderTag is already an NSInteger:

@property (nonatomic,assign) NSInteger* sliderTag;

The first NSLog prints 0 and the 2nd after the add is performed prints 4. Could anyone explain why? It is meant to print 0 the first one, as the point of this variable is to be a counter for setting tags.

Was it helpful?

Solution

Sounds like _sliderTag is a pointer to a type whose size is 4 bytes. Adding 1 to a pointer increments it by the size of the type it points to. Here are two examples that illustrate the difference:

NSInteger foo = 0;
foo += 1;
NSLog(@"result: foo = %d", foo);    // result: foo = 1

NSInteger *bar = 0;                 // note the '*'
bar += 1;
NSLog(@"result: bar = %d", bar);    // result: bar = 4

OTHER TIPS

first, make sure _sliderTag is an int or Integer or int and not Integer* or int*, second, dont print it with %i, but with %d

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top