Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type casting in objective-c, (NSInteger) VS. integerValue

Tags:

casting

xcode

ios

I don't very understand about the diference between (NSInteger)aNumberValue and [aNumberValue integerValue], then do some test. For example, here is a response data from server:

enter image description here

You can see it's an int but the value is hold by NSNumber. I retrieve the data by writting NSInteger count = (NSInteger) dic[@"count"];, and in Xcode debug area, saw this:

enter image description here

it's really a strange value but when I run po count and saw this:

enter image description here

anyway, the value is correct, but another strange thing is:

enter image description here

the number 2 is not less than 100!

Then I try NSInteger a = [dic[@"count"] integerValue] and saw the normal value in Xcode debug area:

enter image description here

and:

enter image description here

So, I am a little bit confused, what's the deference between (NSInteger)aNumberValue and [aNumberValue integerValue]?

like image 959
Allen Avatar asked Jul 03 '26 06:07

Allen


1 Answers

NSNumber is a class; NSInteger is just a typedef of long, which is a primitive type.

dic[@"count"] is a pointer, which means that dic[@"count"] holds an address that points to the NSNumber instance. NSNumber has a method called integerValue which returns an NSInteger as the underlying value that the NSNumber instance represents. So you can conclude that [dic[@"count"] integerValue] gets you a long, and that's how you retrieve the value out of NSNumber.

You don't retrieve the value of NSNumber by casting it to NSInteger. That's because dic[@"count"], as I said, is a pointer. So by writing

NSInteger count = (NSInteger) dic[@"count"];

you are actually casting the pointer itself to an NSInteger, which has nothing to do with the actual represented value. The value 402008592 you see is just a decimal representation of the value of the pointer, which is an address.

The command po is used for printing objects, so lldb will actually try to print out the object at the address of count. That's why you get 2 back using po. You can try p count and you'll get 402008592.

About po count < 100: The expression (count < 100) is evaluated first; since count is really just an NSInteger of 402008592, it will evaluate to false.

like image 102
Renfei Song Avatar answered Jul 06 '26 11:07

Renfei Song