igorastvorov
igorastvorov

Reputation: 47

How does this Objective-C code work?

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

Answers (3)

Amin Negm-Awad
Amin Negm-Awad

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

Louis T
Louis T

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

Marcelo
Marcelo

Reputation: 9944

This works because:

  1. All objects that inherit from NSObject have a description method.
  2. Objective-C doesn't enforce types, so n is actually an NSString and not an NSNumber as you might suppose.

Upvotes: 5

Related Questions