objective c - Odd issues with int and NSInteger -


have spent several hours on , sure i'm missing obvious. i'm new cocoa/objective c , rusty pointers / objects, , appreciate (kindly!) pointing out i'm going wrong.

here code:

.h file:

@property (assign) nsinteger *freetrialcounter; 

.m file

nsinteger = 2; self.freetrialcounter = &(a);     nslog(@"free trial counter: %d", *self.freetrialcounter);  int b = *self.freetrialcounter; nslog(@"b: %d", b); 

here output: free trial counter: 2 b: 1606411536

what missing here? why isn't "b" equal "2"?

the root of problem int , nsinteger can different sizes. so, you're assigning pointer nsinteger property of type nsinteger*, okay (but unusual). however, you're dereferencing value int, happens not same size.

however, think may confused how need declare property hold nsinteger. nsinteger simple integer type, not object, there's no need use pointer refer it. doubly true since seem declaring nsinteger address you're taking on stack, pointer invalid method assignment ends.

you'll better off using plain old nsinteger property , not trying use pointer here. instead:

@property (assign) nsinteger freetrialcounter; //... nsinteger = 2; self.freetrialcounter = a;     nslog(@"free trial counter: %ld", self.freetrialcounter);  nsinteger b = self.freetrialcounter; nslog(@"b: %ld", b); 

note i've changed type of b nsinteger match property type. since they're not same size, mixing 2 can (as you've seen) cause problems. likewise, i've changed format specifier %d %ld match 64-bit size of nsinteger.


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -