0

I had a NSDictionary contains 2 key/value pairs:

NSDictionary *dic = @{@"tag":@2,                //NSNumber
                      @"string":@"someString"}; //NSString

NSLog(@"%i",(int)[dic objectForKey:@"tag"]);      //print out 34
NSLog(@"%i",[dic objectForKey:@"tag"] intValue]); //print out 2

Why does "converting id value to int with (int)"get me the wrong result but not the other way? are they in different levels of conversion?

bluenowhere
  • 2,683
  • 5
  • 24
  • 37

4 Answers4

1

@2 is not an int but a NSNumber you can't cast an NSNumber into an int. You have to use intValue method to get the correct result.

KIDdAe
  • 2,714
  • 2
  • 22
  • 29
1

Why does "converting id value to int with (int)"get me the wrong result but not the other way? are they in different levels of conversion?

id is a pointer type. id pointers point to Objective-C objects in memory. By casting id to (int), you are merely reinterpreting (some of) the pointer's bit pattern as an int, which is quite meaningless. You have to call the proper conversion methods of NSString and NSNumber if you want to reliably get the primitive values out of the Objective-C object.

If you ever seemingly get the "correct" value of 2 in the case of pointer-casting with NSNumber, that may be because the Objective-C runtime makes use of an optimization technique called tagged pointers, whereby small objects are not really created and allocated, but their semantics (the number's bits which the NSNumber object stores) is stuffed into the unused bits of the pointer.

0

The method objectForKey: returns a pointer to the NSNumber object @2, not the value stored in the object itself. So you're typecasting the pointer, not the value 2. In the last line you don't typecast the object but you access a property called intValue which returns the value of the object expressed as an int.

smeis
  • 151
  • 9
0

NSDictionary contains Object with Key value pairs,but you passed int(@2) into object

NSDictionary *dic = @{@"tag":@2,                //NSNumber
                      @"string":@"someString"};

so Change int to NSNumber like

NSDictionary *dic = @{@"tag":[NSNumber numberWithInt:2];,@"string":@"someString"};

and you can get it..

int number = [[dict objectForKey:@"tag"] intValue]; 
Chandan kumar
  • 1,074
  • 12
  • 31