Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd issues with int and NSInteger

Have spent several hours on this and am sure I'm missing something completely obvious. I'm new to cocoa/objective c and rusty with pointers / objects, and thus would greatly appreciate someone (kindly!) pointing out where I'm going wrong.

Here is my code:

.h file:

@property (assign) NSInteger *freeTrialCounter;

.m file

NSInteger a = 2;
self.freeTrialCounter = &(a);   

NSLog(@"Free Trial Counter: %d", *self.freeTrialCounter);

int b = *self.freeTrialCounter;
NSLog(@"B: %d", b);

here is the output: Free Trial Counter: 2 B: 1606411536

What am I missing here? Why isn't "B" equal to "2"?

like image 308
user3643251 Avatar asked Oct 20 '22 08:10

user3643251


1 Answers

The root of the problem is that int and NSInteger can be different sizes. So, you're assigning a pointer to an NSInteger to a property of type NSInteger*, which is okay (but unusual). However, you're dereferencing that value as an int, which happens not to be the same size.

However, I think that you may also be confused about how you need to declare a property to hold an NSInteger. NSInteger is just a simple integer type, not an object, so there's no need to use a pointer to refer to it. This is doubly true since you seem to be declaring the NSInteger whose address you're taking on the stack, so the pointer will be invalid as soon as the method where you do the assignment ends.

You'll be much better off using a plain old NSInteger property and not trying to use a pointer here. Do this instead:

@property (assign) NSInteger freeTrialCounter;
//...
NSInteger a = 2;
self.freeTrialCounter = a;   

NSLog(@"Free Trial Counter: %ld", self.freeTrialCounter);

NSInteger b = self.freeTrialCounter;
NSLog(@"B: %ld", b);

Note that I've also changed the type of b to NSInteger to match the property type. Since they're not necessarily the same size, mixing the two can (as you've seen) cause problems. Likewise, I've changed the format specifier from %d to %ld to match the 64-bit size of NSInteger.

like image 120
Caleb Avatar answered Oct 27 '22 19:10

Caleb