Search code examples
objective-ckey-valueinstance-variableskey-value-coding

Explanation for assigning Objective-C NSNumber object to int variable?


Can anyone explain why this works in Objective-C? I would expect it to give an error since an object is being assigned to an int variable. I get that it does work, and this is great, but I am missing why this is allowed?

int i = [NSNumber numberWithInt:123];

Furthermore, this seems to store the wrong value (ie, on my system when I print out the value of "i" using NSLog I get "252711" instead of 123); however, only when the variable is declared and assigned in my main code. If I declare it as an instance variable of an object and then use Key-Value coding to assign it a value, it works properly:

Object instance variables...

@interface myObject : NSObject
{
    int anInt;
}

Main code...

[myObject setValue:[NSNumber numberWithInt:123] forKey:@"anInt"];
NSLog(@"%@", [myObject valueForKey:@"anInt"]);

This code prints out "123" as expected, but I'm not sure why given that when using a seemingly similar approach above it does not work properly.


Solution

  • it doesnt "work" and there is a compiler warning about it. the reason it can be compiled is that the NSNumber class method numberWithInt returns a pointer, which can be implicitly converted to int. When you print it out you are getting the address where the objective-c object was allocated.

    the SetValue:forKey: method doesnt take an int parameter, it takes an id which is just a pointer to a generic Objective-C object. Key-Value coding is taking care of assigning the intValue of the NSNumber object for you.