Casting type in objective-c, (NSInteger) VS. integerValue
I don't really understand the difference between (NSInteger)aNumberValue
and [aNumberValue integerValue]
, then do some tests. For example, here is the response data from the server:
You can see this int, but the value is being held by NSNumber. I am fetching data by writing out NSInteger count = (NSInteger) dic[@"count"];
and in the debug area of ββXcode saw this:
this is a really strange value, but when I run po count
and see this:
anyway, the value is correct, but one more strange thing:
number 2 is not less than 100!
Then I try NSInteger a = [dic[@"count"] integerValue]
and see a normal value in the Xcode debug area:
and
So, I'm a little confused, what's the reverence between (NSInteger)aNumberValue
and [aNumberValue integerValue]
?
source to share
NSNumber
- class; NSInteger
is just a typedef
of long
, which is a primitive type.
dic[@"count"]
is a pointer, which means it dic[@"count"]
contains an address that points to an instance NSNumber
. NSNumber
has a method integerValue
that returns NSInteger
as the base value that the instance represents NSNumber
. Thus, you can conclude what [dic[@"count"] integerValue]
gets you long
and how you get the value from NSNumber
.
You are not retrieving the value NSNumber
by casting it to NSInteger
. This is because, dic[@"count"]
as I said, is a pointer. So, writing
NSInteger count = (NSInteger) dic[@"count"];
you are actually overlaying a pointer to NSInteger
, which has nothing to do with the actual displayed value. The value 402008592
you see is simply the decimal representation of the pointer value, which is the address.
The command is po
used to print objects, so lldb will actually try to print the object to the address count
. This is why you get 2
help po
. You can try p count
and you will get 402008592
.
A po count < 100
: expression is evaluated first (count < 100)
; since count
it's really just a NSInteger
of 402008592
, it will evaluate to false
.
source to share
The root problem is that Objective-C collection classes can only store Objective-C objects, not primitive types such as float
, int
or NSInteger
.
Hence, it NSNumber
provides a mechanism for storing numbers and booleans in the form of an object.
The value 402008592
looks like an address, so it might be an object NSNumber
containing the value NSInteger
.
Do not confuse the prefix NS
NSInteger
and NSUInteger
; they are still primitive types, not objects like NSNumber
.
source to share