Reputation: 47
Code:
int main(int argc, const char * argv[]) {
id idObject = @"12345";
NSNumber *n = idObject;
NSLog(@"%@\n", [n description]);
return 0;
}
It prints "12345". How? I guess it's because Objective-C uses dynamic binding. Thus, decision which method to choose is made at run-time and this decision is based on the name of the method (selector) and the receiver object. Maybe the receiver object gets known due to "isa" pointer... ?
Upvotes: 1
Views: 116
Reputation: 16650
You are right.
The code works, because n
refers to an object that understands the message description
. (The object is a instance object of class NSString
and these objects understand that message.)
The type of the object reference n
(id
, NSString*
, NSNumber*
, whatever
) is without any meaning for the dispatching process.
At runtime you can collect many information about objects and its types. You cannot collect information about object references. (There is a single case, but this is not important.)
Upvotes: 3
Reputation: 1313
To add:
You're not actually typecasting by setting idObject
to be referenced by NSNumber * n
. The compiler doesn't know what type id
should be, so it allows you to assign it to anything.
With your code snippet running you can see a bit more on how this is played out:
And then for comparison (creating an NSNumber from the string literal):
Upvotes: 2
Reputation: 9944
This works because:
NSObject
have a description
method.n
is actually an NSString
and not an NSNumber
as you might suppose.Upvotes: 5