Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum two NSInteger gives incorrect result

Tags:

objective-c

Im haveing a problem suming two NSInteger, I have tried with simple int but cant find the answer. I Have this on my header file:

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

The on my implementation fiel I have:

-(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);

}

The las NSLog always prints 0 + 1 = 4

Also if if do:

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

Several times i get: 4, 8, 12.

So it is skiping by four, but I can't get to understand why.

like image 875
Hector A Centeno Avatar asked Jan 21 '13 18:01

Hector A Centeno


3 Answers

You are declaring your photoCount instance var as pointer to NSInteger. But NSInteger is a scalar type.
Remove the asterisk in your .h file and try again.

Replace

NSInteger *photoCount; 

with

NSInteger photoCount; 
like image 87
Thomas Zoechling Avatar answered Jan 03 '23 12:01

Thomas Zoechling


You're printing out a pointer object I believe as you've declared it as

NSInteger* photocount;

Try changing it to

int photocount;

doing a variable++ on an integer adds the size of a pointer which is 4 bytes on iOS.

like image 43
sradforth Avatar answered Jan 03 '23 12:01

sradforth


You used pointer to NSInteger...

Change it to NSInteger photoCount;

NSInteger is just an int, and you are treating it as an wrapper object. Pointer in not required.

like image 42
Anoop Vaidya Avatar answered Jan 03 '23 11:01

Anoop Vaidya