A sum of two NSInteger gives an incorrect result

I had the problem of summing two NSInteger, I tried with a simple int, but could not find the answer. I have this in my header file:

@interface ViewController : UIViewController {
NSMutableArray *welcomePhotos;
NSInteger *photoCount;        // <- this is the number with the problem
//static int photoCount = 1;
}

In my runtime, I:

-(void)viewDidLoad{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

    photoCount = 0;
    welcomePhotos = [NSMutableArray array];


    int sum = photoCount + 1;

    NSLog(@"0 + 1 = %i", sum);

}

las NSLog always prints 0 + 1 = 4

Also if do:

if (photoCount < [welcomePhotos count]){
    photoCount++;
    NSLog(@"%i", photoCount);
}else{
    photoCount = 0;
}

Several times I get: 4, 8, 12 .

So this is a four pass, but I can’t understand why.

+5
source share
3 answers

You are printing a pointer object, which I believe since you declared it as

NSInteger* photocount;

Try changing it to

int photocount;

Running a ++ variable for an integer adds a pointer size that is 4 bytes in iOS.

+3
source

photoCount NSInteger. NSInteger - .
.h .

NSInteger *photoCount; 

NSInteger photoCount; 
+5

You used a pointer to NSInteger...

Change it to NSInteger photoCount;

NSInteger is just an int, and you see it as a wrapper object. A pointer is not required.

+3
source

All Articles