问题描述:

I know that you send messages to objects using [ ], and it is then translated to objc_msgSend()which needs a pointer to object as its first argument and second argument needs a selector.

But what about messaging classes like

[myClass doSomething];

It is not a pointer to object, so how does it work?

网友答案:

I am assuming that myClass is (literally) the name of a class (though usually classes start with a capital letter; I'll assume this is a class that doesn't follow the naming convention).

There are two cases of the message sending syntax in Objective-C. One, which you referred to, is if the left side is an expression which evaluates to a pointer to an object; the message is sent to that object. The second, is if the left side is an identifier which is the name of a class, then the compiler will send the message to the class object for that class. More technically, the compiler will pass a pointer to the class object as the first argument to objc_msgSend(). This is possible since it is the compiler which arranges the structure and location of the class object for each class, so it knows the address of that class object.

Intuitively, you can think of [myClass doSomething]; as similar to

Class foo = objc_getClass("myClass");
[foo doSomething];

or

Class foo = NSClassFromString(@"myClass");
[foo doSomething];

except that it doesn't need to do a runtime lookup to get a pointer to the class object -- the compiler knows the pointer at compile time.

网友答案:

Mike Ash has a great explanation of how objc_msgSend works: Friday Q&A 2012-11-16: Let's Build objc_msgSend.

网友答案:

Actually, when you send a message to a class, you are actually sending that message to a class object, which behaves as any other object with some limitations.

From Apple's reference:

In Objective-C, a class is itself an object with an opaque type called Class. Classes can’t have properties defined using the declaration syntax shown earlier for instances, but they can receive messages.

网友答案:

The runtime converts the message to a SEL then checks to see if that class responds to a message with that SEL including superclass inherited methods. If it responds it will perform the method.

相关阅读:
Top